Recursive Generics

Did you know it is possible to constrain a generic type parameter to be a subclass of the generic in question? I discovered this trick a while ago and recently leveraged it in my own MVVM framework (more on that later). Basically, I used it to create a generic base ViewModel object that used the static reflection trick for raising property changed notifications. Here is how it looks

    public class ViewModelBase<T>:INotifyPropertyChanged
        where T:ViewModelBase<T>
    {
        protected void NotifyPropertyChanged(Expression<Func<T,object >>propertyExpression)
        {
            var prop = propertyExpression.Body as MemberExpression;
   #if DEBUG
            if(prop==null)
                throw new ArgumentException("The passed in expression must be a Property Accessor", "propertyExpression");
   #endif
            if(PropertyChanged!=null)
                PropertyChanged(this,new PropertyChangedEventArgs(prop.Member.Name));
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

So if I have a subclass of ViewModelBase it would specify itself like so

public class SomeViewModel:ViewModelBase<SomeViewModel>

This allows the T in Expression<Func<T,object>> to refer strongly to SomeViewModel and see the properties on the SomeViewModel class. While I’ve only had to use this technique in a few cases. It’s handy to know that even though it seems quirky, it is possible to do.

Published Wednesday, November 10, 2010 8:47 AM by Mike Brown
Filed under: , ,

Leave a Comment

(required) 
(required) 
(optional)
(required)