Dependency Properties – Don’t use Reference Types for Defaults

I thought I was going crazy! Data from one class was magically appearing in another instance. After double checking all code paths and walking through in a debugger, I found the cause…

This is a user control, with a dependency property. The DP is a collection. Notice line 33 in the sample below. I am setting the “default value” for the property to an instance of a collection.

BAD, BAD, BAD.

It all makes sense now, given that a DP definition is static. It caught me off guard though because I’m used to setting the default value as part of the DP snippet. I wanted the collection to be instantiated with each new instance, so why not? Well, it does bad things is why not. In my case, other instances of the user control mysteriously had data in them that I never put there. The collection was effectively a static instance. Additionally, it would have been a GC root and prevented garbage collection of the collection and anything it referenced.

Lesson learned

  1. Don’t use reference types as default values in Dependency Properties!
  2. Initialize in the constructor instead.

Sample

Here’s a working sample of reference types in a dependency property that you can past into LinqPad to demonstrate the issue. You’ll need to add references to a WindowsBase.dll and add namespace imports for System.Windows and System.Collections.ObjectModel for it to run. (just hit F4 in linqpad to see these options).

http://pastebin.com/embed_js.php?i=SBJZbzSG

 

Cheers!

One thought on “Dependency Properties – Don’t use Reference Types for Defaults

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: