find a location for property in a new city

Monday, 28 February 2011

Multiple generic constraints in C#

I had some trouble using my nice new generic class in C#. I want to ensure one of the types passed in inherited from a particular class. This class can be instantiated using the new key word however the compile time is not aware of this

I found, using this unnatural syntax, it is possible to constrain the type parameters in multiple ways. Like so:

public class MyClass <T, U> : MyBaseClass <T> where T : class where U : AnotherClass, new()
{
    public AnotherClass AnotherClass { get; set; }
    public MyClass()
    {
        AnotherClass = new U();
    }
    //my class
}

This works fine and can be very useful at times

Follow britishdev on Twitter

No comments:

Post a Comment