Trying to define constraint on class, but get error:
public class Utilities3<T> where T : IComparable
{
public T Max<T>(T a, T b)
{
return a.CompareTo(b) > 0 ? a : b;
}
}
'T' does not contain a definition for 'CompareTo' and no extension method 'CompareTo' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
Cannot resolve symbol 'CompareTo'

While constraint on function works fine:
public class Utilities2<T>
{
public T Max<T>(T a, T b) where T : IComparable
{
return a.CompareTo(b) > 0 ? a : b;
}
}
Why constraint on class not working?
The issue is that you've redefined T on the method and that hides the T defined on the class. So you either need the constraint on the method or more likely you shouldn't redefine the generic type.
public class Utilities3<T> where T : IComparable
{
public T Max(T a, T b)
{
return a.CompareTo(b) > 0 ? a : b;
}
}
You typically only define generic types on either a class or it's methods. And if for some reason you do need to define them in both places it would be better to give them unique names unless you specifically want the hiding behavior, but that's very unlikely.
This line of code:
public T Max<T>(T a, T b)
Defines a new < T> constraint which overwrites the one that you use for the class. Remove this < T> in method and you'll be using a class constraint instead
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With