I have a generic class that takes a type T. Within this class I have a method were I need to compare a type T to another type T such as:
public class MyClass<T>
{
public T MaxValue
{
// Implimentation for MaxValue
}
public T MyMethod(T argument)
{
if(argument > this.MaxValue)
{
// Then do something
}
}
}
The comparison operation inside of MyMethod fails with Compiler Error CS0019. Is it possible to add a constraint to T to make this work? I tried adding a where T: IComparable<T> to the class definition to no avail.
Adding constraint to make sure that the type implements
IComparable<T>is a way to go. However, you cannot use the<operator – the interface provides a methodCompareToto do the same thing:If you needed other numeric operators than just comparison, the situation is more difficult, because you cannot add constraint to support for example
+operator and there is no corresponding interface. Some ideas about this can be found here.