Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How I can compare two values of same generic type?

Following code won’t compile:

class Test<T> where T : class, IComparable
{
    public bool IsGreater(T t1, T t2)
    {
        return t1 > t2; // Cannot apply operator '>' to operands of type 'T' and 'T'
    }
}

How I can make it work? I want it to work for T = int, double, DateTime, etc.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The IComparable interface that you have used here as the type constraint gives you a CompareTo method. So you can do something like this:

public bool IsGreater(T t1, T t2)
{
    return t1.CompareTo(t2) > 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading