Note that there are some explanatory texts on larger screens.

plurals
  1. POCan't operator == be applied to generic types in C#?
    primarykey
    data
    text
    <p>According to the documentation of the <code>==</code> operator in <a href="http://msdn.microsoft.com/en-us/library/53k8ybth.aspx" rel="noreferrer">MSDN</a>, </p> <blockquote> <p>For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings. User-defined value types can overload the == operator (see operator). So can user-defined reference types, although <strong>by default == behaves as described above for both predefined and user-defined reference types.</strong></p> </blockquote> <p>So why does this code snippet fail to compile?</p> <pre><code>bool Compare&lt;T&gt;(T x, T y) { return x == y; } </code></pre> <p>I get the error <em>Operator '==' cannot be applied to operands of type 'T' and 'T'</em>. I wonder why, since as far as I understand the <code>==</code> operator is predefined for all types?</p> <p><strong>Edit:</strong> Thanks, everybody. I didn't notice at first that the statement was about reference types only. I also thought that bit-by-bit comparison is provided for all value types, which I now know is <em>not</em> correct.</p> <p>But, in case I'm using a reference type, would the <code>==</code> operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one?</p> <p><strong>Edit 2:</strong> Through trial and error, we learned that the <code>==</code> operator will use the predefined reference comparison when using an unrestricted generic type. Actually, the compiler will use the best method it can find for the restricted type argument, but will look no further. For example, the code below will always print <code>true</code>, even when <code>Test.test&lt;B&gt;(new B(), new B())</code> is called:</p> <pre><code>class A { public static bool operator==(A x, A y) { return true; } } class B : A { public static bool operator==(B x, B y) { return false; } } class Test { void test&lt;T&gt;(T a, T b) where T : A { Console.WriteLine(a == b); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload