Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constraint on class

Tags:

c#

constraints

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'

error

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?

like image 401
vico Avatar asked May 06 '26 15:05

vico


2 Answers

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.

like image 182
juharr Avatar answered May 09 '26 03:05

juharr


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

like image 44
Fabjan Avatar answered May 09 '26 03:05

Fabjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!