Tuesday, June 25, 2013

Self-referencing Generic Type Constraint

Here is a simple and nice piece of code where I found the use of a self-referencing generic type constraint useful.

This interface is used to represent a hierarchy. The generic type parameter T is constrained to IHierarchical<T>. Although at first glance it might seem like a recursion, of course, it isn't. It just requires the type argument to be implementing the same interface.

Looking around for other guys that use this pattern, I found this post by Eric Lippert who more or less discourages it. Although I agree with him that this pattern can be confusing if not used properly, I still think it can be quite elegant and expressive if used in suitable context.

I think this hierarchy example is a good fit for the pattern.

Side note on the actual use of this interface:
As I said, I use this to represent a hierarchy. In my code this interface is actually implemented by several classes that participate in several hierarchies. The use of the Parent pointer seems redundant, but in my case it is not as the classes that implement this interface are actually SharePoint content types, so the Children property is actually a multi-lookup column in SharePoint and the Parent pointer is the column at the other end of the relationship. Both values are populated by executing a single Linq2SharePoint query.

Friday, March 8, 2013

Two way data binding on a DependencyProperty

I was creating a WPF UserControl today which (among other things) was exposing a DependencyProperty for use in data binding. The problem I came across was that it didn't bind two-way by default and for a while I couldn't figure out either why nor what was the most slick way to go about it.

So here is the trick in case anyone stumbles upon this post while facing a similar problem. In the metadata for your DependencyProperty, don't forget to set the BindsTwoWayByDefault property to true.