42

Why did Microsoft go the route of making dependency properties and dependency objects instead of using reflection and maybe attributes?

Rob Hruska
  • 111,282
  • 28
  • 160
  • 186
Mr Bell
  • 8,864
  • 18
  • 77
  • 124
  • So where are default values of dependency properties gets stored. They were also consuming memory, aren't they? Also if we change "Text" dp of a textbox control say, then the changed value will get stored in Hashtable of that object (particular textbox) only? If this is the case, then default value + changed value..doubling the memory..ufff. Let me know your views, Regards Rakesh www.qtricks.com –  Dec 03 '11 at 10:09
  • @Rajesh Kumar: The default values are stored statically. Hence the reduced footprint because you have just one value for all instances. – user879355 Jul 04 '12 at 08:14

2 Answers2

67

This helped me understand the reasoning:

The main difference is, that the value of a normal .NET property is read directly from a private member in your class, whereas the value of a DependencyProperty is resolved dynamically when calling the GetValue() method that is inherited from DependencyObject.

When you set a value of a dependency property it is not stored in a field of your object, but in a dictionary of keys and values provided by the base class DependencyObject. The key of an entry is the name of the property and the value is the value you want to set.

The advantages of dependency properties are as follows:

Reduced memory footprint

It's a huge dissipation to store a field for each property when you think that over 90% of the properties of a UI control typically stay at its initial values. Dependency properties solve these problems by only store modified properties in the instance. The default values are stored once within the dependency property.

Value inheritance

When you access a dependency property the value is resolved by using a value resolution strategy. If no local value is set, the dependency property navigates up the logical tree until it finds a value. When you set the FontSize on the root element it applies to all textblocks below except you override the value.

Change notification

Dependency properties have a built-in change notification mechanism. By registering a callback in the property metadata you get notified, when the value of the property has been changed. This is also used by the databinding.

From: WPF Tutorials.

Kyle Rosendo
  • 23,930
  • 7
  • 75
  • 114
  • 1
    Thanks for the great answer. Even after reading all the MSDN documentation on DPs, I was still a little mystified until I read your response. – Mike Chamberlain Dec 06 '10 at 01:05
8

Dependency properties solve a different usage scenario than reflection and attributes would solve.

Dependency properties provide a single, consistent API for doing things that standard properties cannot handle.

Reed Copsey
  • 522,342
  • 70
  • 1,092
  • 1,340