DependencyProperty initialization gotcha

There’s something wrong here:

  public class Dude : DependencyObject
  {
    public IList<string> Buddies
    {
      get
      {
        return (IList<string>) GetValue( BuddiesProperty );
      }
      set
      {
        SetValue( BuddiesProperty, value );
      }
    }

    public static DependencyProperty BuddiesProperty = DependencyProperty.Register(
      "Buddies",
      typeof( IList<string> ),
      typeof( Dude ),
      new PropertyMetadata( new List<string>() ) );  
  }

We’ve got a class with a list of strings as a property. Because we want to set the property in XAML, use data binding, and all the goodness, we use a DependencyProperty to store it. Looks pretty standard, hu?

Dude bob = new Dude();
Dude jack = new Dude();

bob.Buddies.Add( "jack" );
jack.Buddies.Add( "bob" );

Assert.That( bob.Buddies, Is.EqualTo( 1 ) );

Surprise! Expected: 1, Actual: 2. Let the wild guesswork begin!

Hint: this one fails as well.

Assert.That( bob.Buddies, Is.Not.SameAs( jack.Buddies ) );

DependencyProoperties are static. Hence, the default value for the DependencyProperty is static as well: all instances that use the DependencyProperty use the _same_ default – in this case, the same List. When a new string is added, it is added to all instances.

Corrected version: move the initialization of the collection to the instance constructor.

  public class Dude : DependencyObject
  {
    public Dude()
    { 
      Buddies = new List<string>();
    }

    public IList<string> Buddies
    {
      get
      {
        return (IList<string>) GetValue( BuddiesProperty );
      }
      set
      {
        SetValue( BuddiesProperty, value );
      }
    }

    public static DependencyProperty BuddiesProperty = DependencyProperty.Register(
      "Buddies",
      typeof( IList<string> ),
      typeof( Dude ),
      new PropertyMetadata( null ) );  
  }
Advertisements
About

Christian is a software architect/developer. He lives in Germany, reads a lot, and likes cycling.

Tagged with:
Posted in Coding
One comment on “DependencyProperty initialization gotcha
  1. alainbryden says:

    Holy crap this one sure got me good. Thanks for confirming my suspicions!

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

%d bloggers like this: