C# WTF? Can anyone explain the strange behaviour?

Posted by partizan on Stack Overflow See other posts from Stack Overflow or by partizan
Published on 2010-03-24T15:27:16Z Indexed on 2010/03/24 15:43 UTC
Read the original article Hit count: 183

Filed under:
|

Hi, guys. Here is the example with comments:

    class Program
{
    // first version of structure
    public struct D1
    {
        public double d;
        public int f;
    }

    // during some changes in code then we got D2 from D1
    // Field f type became double while it was int before
    public struct D2 
    {
        public double d;
        public double f;
    }

    static void Main(string[] args)
    {
        // Scenario with the first version
        D1 a = new D1();
        D1 b = new D1();
        a.f = b.f = 1;
        a.d = 0.0;
        b.d = -0.0;
        bool r1 = a.Equals(b); // gives true, all is ok

        // The same scenario with the new one
        D2 c = new D2();
        D2 d = new D2();
        c.f = d.f = 1;
        c.d = 0.0;
        d.d = -0.0;
        bool r2 = c.Equals(d); // false, oops! this is not the result i've expected for        
      }
}

So, what do you think about this?

© Stack Overflow or respective owner

Related posts about c#

Related posts about floating-point