Search code examples
c#genericsgeneric-method

C# incompatibility in two T types in generic method which return T type


I am trying to return max value of a T[] array by using following method. I don't understand why compiler complains here T max = _genericList[0]; that throws error cannot implicitly convert ...\GenericList(9) to ...\GenericList(123).

Why these two are different? I want to use the T[] of some GenericList class inctance to interpolate through it and find the maximum/minimum. How is that possible?

internal class GenericList<T>
{
    private T[] _genericList;
    private int _count;
    private int _listInnitialLength;

public GenericList(int listLength)
    {
        _genericList = new T[listLength];
        _count = 0;
        _listInnitialLength = listLength;
    }

    public T Max<T>() where T : IComparable
    {
        T max = _genericList[0];
        foreach (T item in _genericList)
        {
                if (Comparer<T>.Default.Compare(item, max) > 0)
                {
                    max = item;
                }
        }
        return max;
    }
}

Solution

  • Your T in method Max<T> is not the one defined in your class GenericList<T>, even they have a same name. I think you should move the constraint to the class and make Max method non-generic.

    internal class GenericList<T> where T : IComparable
    {
        //....
        public T Max()
        {
            //....
        }
    }