Unconstrained Generic comparison should be allowed

P

puzzlecracker

Unlike C++, in Csharp you're only allowed to compare a generic type T
with null, if the method it's passed in not implementing
IComparable<T> or , IEquatable<T> (still don't know why we need these
two radically similar interfaces). In other words, Csharp enforces
people to not make mistake, whereas C++ follows the philosophy "if you
make a stupid mistake, pay for it, and in the future you won't do it
again." In my opinion, comparing a type that doesn't support
comparison is a stupid mistake. All these checks and enforcements
introduced by C# is likely to burden compiler tremendously.

Seriously, why are comparisons are not allowed if mentioned interfaces
are not implemented, even if type supports the comparison?
 
M

Marc Gravell

puzzlecracker wrote:

The simplest option here would be to use Comparer<T>.Default.Compare -
job done. C# generics do not support operators, but you can hack them
toegether if you want; I've done this in the past here (using .NET 3.5):

http://www.pobox.com/~skeet/csharp/miscutil/usage/genericoperators.html

(includes the comparison operators)

Interestingly, C# 4.0 promises to support operators on the new "dynamic"
type, which would be a short-cut, but probably noticeably slower than
either of the above approaches. I can't tell yet, as it isn't in the CTP
build...

Marc
[C# MVP]
 
J

Jon Skeet [C# MVP]

puzzlecracker said:
Unlike C++, in Csharp you're only allowed to compare a generic type T
with null, if the method it's passed in not implementing
IComparable<T> or , IEquatable<T> (still don't know why we need these
two radically similar interfaces).

Just to comment on why we need two interfaces: in many cases it's not
really useful to *order* items, but it *is* useful to be able to
compare them for equality.

Is red a "bigger" colour than yellow, or not? It's a daft question -
but we know they're *different* to each other.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top