Search code examples
c#genericsconstraints

How do I add Generic constraints?


I have the following situation in C#:

class MyGenericClass<T>
{
    public void do()
    {
    }
}

class SpecificFooImpl : MyGenericClass<Foo>
{
     public void otherStuff()
     {
     }
}

Now I want to write a generic method which can return only MyGenericClass<T> or specific implementations. I would write something like:

var v1 = GetMyClass<MyGenericClass<Foo>>();
var v2 = GetMyClass<MyGenericClass<Bar>>();
var v3 = GetMyClass<SpecificFooImpl>();

I could use the following signature but it have no constraints on the type:

public T GetMyClass<T>();
//I don't want to write
//var v4 = GetMyClass<AnyOtherTypesWhichNotExtendMyGenericClass>();

Is there any elegant mode to solve the problem?


Solution

  • Add a where : clause after the definition, then you can define what should be obeyed.
    I've said it must be a class but you can add a base class or interface as a constraint.

    class MyGenericClass<T> where T : class, IYourCommonInterface
    {
        public void do()
        {
        }
    }
    

    References:
    See MSDN on constraints: http://msdn.microsoft.com/en-us/library/d5x73970.aspx