JasonBaby
JasonBaby

Reputation: 13

How to Check if a Generic Type is IComparable then Compare if so?

I'm trying to figure out how to do something like the pseudo-code below:

private void test<T>(T a, T b)
{
    if (a is IComparable<T> && b is IComparable<T>)
    {
        int result = a.CompareTo(b);
        // do something with the result
    }
    else
    {
        // do something else
    }
}

How can I achieve that in C# ?

Upvotes: 1

Views: 883

Answers (1)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23208

You can use is type pattern to assign the result to a variable and use it to call Compare. You also don't need to cast b to IComparable<T>, since CompareTo accepts parameter of T type (and b is T already)

if (a is IComparable<T> comparable)
{
    int result = comparable.CompareTo(b);
    // do something with the result
}

Another option is to apply a generic constraint with IComparable<T> interface

private void test<T>(T a, T b) where T : IComparable<T>
{
    var result = a.CompareTo(b);
    // do something with the result
}

Upvotes: 4

Related Questions