Note that there are some explanatory texts on larger screens.

plurals
  1. POUnexpected behavior in c# generic method on .Equals
    text
    copied!<p>Why does the Equals method return a different result from within the generic method? I think that there's some automatic boxing here that I don't understand.</p> <p>Here's an example that reproduces the behavior with .net 3.5 or 4.0:</p> <pre><code>static void Main(string[] args) { TimeZoneInfo tzOne = TimeZoneInfo.Local; TimeZoneInfo tzTwo = TimeZoneInfo.FindSystemTimeZoneById(tzOne.StandardName); Console.WriteLine(Compare(tzOne, tzTwo)); Console.WriteLine(tzOne.Equals(tzTwo)); } private static Boolean Compare&lt;T&gt;(T x, T y) { if (x != null) { return x.Equals(y); } return y == null; } </code></pre> <p>Output:</p> <pre><code>False True </code></pre> <p><strong>Edit:</strong> This code works as desired without many compromises:</p> <pre><code>private static Boolean Compare&lt;T&gt;(T x, T y) { if (x != null) { if (x is IEquatable&lt;T&gt;) { return (x as IEquatable&lt;T&gt;).Equals(y); } return x.Equals(y); } return y == null; } </code></pre> <hr> <p><strong>Followup</strong>: I filed a <a href="https://connect.microsoft.com/VisualStudio/feedback/details/707019/timezoneinfo-does-not-override-the-equals-object-method" rel="nofollow">bug via MS Connect</a> and it has been resolved as fixed, so it's possible this will be fixed in the next version of the .net framework. I'll update with more details if they become available.</p> <p><strong>PS</strong>: This appears to be fixed in .net 4.0 and later (by looking at the disassembly of TimeZoneInfo in mscorlib).</p>
 

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