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.
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.
See more on this question at Stackoverflow