This is a mirror of official site: http://jasper-net.blogspot.com/

Dependency Properties

| Wednesday, August 10, 2011
Dependency properties are like the sewers, electric wires and pipes running under the streets of a big city. You can ignore them, you can even be oblivious to their existence, but they make all the magic happen and when something breaks you really want to understand them.

Before we begin exploring Dependency Properties, let’s review Properties themselves. To do that, we go back into the dark early days of C++ when what we had available in a class were methods and  member variables (fields).

When I was a boy, there were no properties, VCRs or digital watches…

Data Hiding

Back in these dark days, we wanted to store values in fields, but we didn’t want clients (methods that use our values) to have direct access to those fields (if nothing else, we might later change how we store the data).  Thus we used accessor methods.

The accessor methods had method semantics (you used parentheses) and so data hiding was explicit and ugly. You ended up with code that looked like this:

int theAge = myObject.GetAge();

 

which just seems all wrong , what you wanted was

int theAge = myObject.age;

 

Field Syntax with Method Semantics

Enter properties.  Properties have the wonderful characteristic of looking like a field to the consumer, but looking like a method to the implementer. Now you can change the way the Property is “backed” without breaking the consumer, but the consumer gets the right semantics. Nice.

The class with the property looks like this

private int _age;
public int Age { get { return _age; } set { _age = value; } }

 

Age is the property, _age is the backing variable.  The consumer can now write

int theAge = myObject.Age;


Read more: Jesse Liberty
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=http://jesseliberty.com/2011/08/08/dependency-properties/

Posted via email from Jasper-net

0 comments: