3

I want to write a generic method:

void Foo<T>(IList<T> list)

In the method, I want to compare elements of list either by using operator < if T is primitive type or Compare() if T implements IComparable.

Is this possible? If not, it means C# generics is very limited in use I think.

4
  • What I mean is: in C++, it is up to compiler to check if a call is valid at instantiation. But C# has stronger requirement and hence narrow use of generics. Commented Jan 15, 2014 at 14:00
  • You say "narrow" I say "absolutely fine in the vast majority of cases where I've wanted to use generics." Commented Jan 15, 2014 at 14:07
  • @Jon Skeet, really "absolutely fine", even when you need so tricky way to call operator+ in a generic method? (Yes, I read your other article just now). IMO, C# at least needs some contract specification for generics that say "T requires to have operator+ overloaded" or "T requires to have method of such signature". Commented Jan 15, 2014 at 14:14
  • It's absolutely fine in the vast majority of cases where I've wanted to use generics, because in that vast majority of cases I haven't wanted to call operator+ - it's as simple as that. You say that C# "needs" some contract specification - you might like it (and so might I) but that's not the same as "needing" it. Commented Jan 15, 2014 at 14:21

1 Answer 1

14

Is this possible? If not, it means C# generics is very limited in use I think.

Even if it weren't possible, generics can be used in many many situations.

However, it's really simple given that all the primitive types implement IComparable<T>;

void Foo<T>(IList<T> list) where T : IComparable<T>
{
    T x = ...;
    T y = ...;
    if (x.CompareTo(y) < 0)
    {
        ...
    }
}

Note that this will not introduce boxing operations. I'd expect the JITted code for primitive types to end up having very similar performance to hardcoding it to use < or >.

Now this is a slightly special case, because there's an interface which is roughly equivalent to those operators. What isn't as easy is using arithmetic operators (+, - etc). See the article on my web site for a few approaches to this.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, @Jon Skeet You answered to my question and also confirmed that C# generics is not as flexible and powerful as C++ template.
@Sheen: They're not the same, and weren't meant to be the same. There are benefits of each approach, and each is suitable for the design of the language it's part of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.