Search code examples
c#genericsinterfaceicomparable

Binding a generic class to a specific interface


I am trying to make a generic class. Is there a way to make a constraint so that only objects that implement IComparable can be passed into my generic. For example:

public class MyClass<T>
{

}

public class MyFooClass
{
}

public class MyComparableFooClass : IComparable
{
    public int Compare(MyComparableFooClass q) 
    { 
        return 0;
    }
}

public class MyMainClass()
{
    private MyClass<int> _myIntClass; // This is okay since int implements IComparable
    private MyClass<MyComparableFooClass> _myComparableFooClass // This should be okay too since int implements IComparable
    private MyClass<MyFooClass> _myFooClass; // This should get a compile error since MyFooClass doesn't implement IComparable
}

Hopefully my example is clear. I just want MyClass<T> to allow objects that implement IComparable. I understand that the where constraint only works with classes, if I'm not mistaken. Is this possible or can someone offer a work around?


Solution

  • Generic constraint's work with interfaces too. From the documentation

    where T : class The type argument must be a reference type, including any class, interface, delegate, or array type.

    So you can use the keyword where with IComparable:

    public class MyClass<T> where T : IComparable
    {
    
    }