Search code examples
c#icomparable

Error while passing IComparable<T> to CompareTo


I have a following code:

public class Foo<T>
{
    private IComparable<T> a { get; set; }
    
    public int foo(IComparable<T> b)
    {
        return a.CompareTo(b); // compile error : Argument type 'System.IComparable<T>' is not assignable to parameter type 'T?'
    }
}

Argument type 'System.IComparable' is not assignable to parameter type 'T?'

How can I avoid this error?


Solution

  • Add a generic constraint at the class level to ensure that T implements IComparable<T>. Then replace IComparable<T> in the property and parameter type with just T.

    public class Foo<T> where T : IComparable<T>
    {
        private T a { get; set; }
    
        public int foo(T b)
        {
            return a.CompareTo(b);
        }
    }