tags:

views:

119

answers:

2

Hi,

Here is my simple code:

T a;
T b;

if (a == b)
// sth.
else
// sth. else

When I try to compile, I get an error saying the == operator is invalid for generic types. So I have to use the object.Equals() method.

Doesn't the == operator actually call the Equals method of object? Why can I use the Equals method of two generic types but not the == operator?

+2  A: 

The == operator is not defined all possible values of T [thanks Daniel] (or on any constraints you may have placed on T, I assume), so you can't use it. You can only call operators, methods, properties on T that can be called on ALL possible types represented by T.

operator == calls 'Equals' in many cases, but that doesn't mean they are the same thing.

Philip Rieck
Actually, operator == *is* defined on object, just not on structs. And for most reference types, == does *not* call .Equals. The former usually implements identity comparison (except for immutable types) and the latter usually implements value comparison.
Daniel Pryden
A quick survey with ndepend shows that most reference types in the BCL don't define operator== - giving them ReferenceEquals not value comparison behavior. It's interesting to note that operator== isn't actually defined on `object` as far as I can see - instead I believe the c# (or other language) compilers end up compiling to `.ceq` which for reference types means a reference-equality style check.
Philip Rieck
+7  A: 

operator == must be overloaded in structs in order to be used, hence a completely unconstrained type parameters cannot use it. You can constrain the function to class to allow default reference comparison:

    public void Foo<T>() where T : class {
        T a = default(T);
        T b = a;

        if(a == b)
            System.Diagnostics.Debug.WriteLine("");
        else
            System.Diagnostics.Debug.WriteLine("");
    }

The above code works because by default, reference types can be used with operator ==:

For reference types other than string, == returns true if its two operands refer to the same object.

This is why if (new object() == new object()) {} compiles, even though System.Object doesn't overload operator ==.

Igor Zevaka