Dependency Properties are Too Painful

By Michael Flanakin @ 3:16 PM :: 16244 Views :: .NET :: Digg it!

When I first started using dependency properties and routed events in .NET 3.0, I hoped things would be simplified. Given all the compile-time enhancements in .NET 3.5, that was a perfect time to greatly simplify these. Sadly, nothing changed and to my surprise, .NET 4.0 maintained the status quo. For instance, here’s a simple dependency property in Silverlight:

public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(MyControl), new PropertyMetadata("Hello", TitleProperty_Changed));

public string Title


    get { return (string)GetValue(TitleProperty); }

    set { SetValue(TitleProperty, value); }


Every time I type this, I cringe. What I should be typing is something like the this:

[DependencyProperty(DefaultValue="Hello", Changed=MyControl.TitleProperty_Changed)]

public string Title { get; set; }

The one trick is that the compiler would have to see the DependencyPropertyAttribute and convert that to the full code above. This could be further simplified with a new keyword (e.g. public dependency string or public attached string) to signify a property is a dependency property, but we'd still need a way to specify custom metadata, like the default value and change events -- of course, we already have a DefaultValueAttribute, so that should be partially sufficient.

There's really no way you can argue the simplicity of this approach. Hell, the dependency property registration line is 68 characters longer than the entire simplified alternative. That's 282 vs 106 characters. Which would you prefer?

Ideally, this same concept would be added for INotifyPropertyChanged and it's related interfaces. By simply stating that I want to use this interface, .NET should know what to do. All this code is just ceremony I'd rather avoid.