JavaSa
JavaSa

Reputation: 6241

Generic types comparison

I have two objects of generic type T.

T x , T y

I want to be able to do comparison like:

if (x >= y)

Therefore I try to use the compareTo method which is missing until I add the constraint where T:IComparable. Only then I see it in the intellisence.

Not sure why only then I see it and not before writing it.

Upvotes: 0

Views: 108

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500085

Not sure why only then I see it and not before writing it.

Because until that constraint exists, the compiler has no idea what members are available on T, other than those which are present as part of object. You wouldn't expect to be able to write:

object x = GetObjectFromSomewhere();
object y = GetObjectFromSomewhere();
int comparison = x.CompareTo(y);

would you? C# is a statically typed language (aside from dynamic) - the compiler has to know which members you're talking about when you use them.

As an aside, if the types you're interested in implement IComparable<T> rather than just the non-generic IComparable, that would be a better constraint. It performs better (because it can avoid boxing) and it's more type-safe (as it prevents you from trying to compare unrelated types).

Upvotes: 8

Related Questions