== Operator overload when inserting an object

The output of the following code is as follows:

not equal

Note the difference in type x and xx and that == operator overloading is performed only in the second case, and not in the first.

Is there a way to overload the == operator so that it always runs when comparing between instances of MyDataObejct.

Edit 1: # here I want to redefine the == operator on MyDataClass, I'm not sure how to do this, so that case1 also runs the overloaded implementation ==.

class Program {
    static void Main(string[] args) {
        // CASE 1
        Object x = new MyDataClass();
        Object y = new MyDataClass();
        if ( x == y ) {
            Console.WriteLine("equal");
        } else {
            Console.WriteLine("not equal");
        }

        // CASE 2 
        MyDataClass xx = new MyDataClass();
        MyDataClass yy = new MyDataClass();
        if (xx == yy) {
            Console.WriteLine("equal");
        } else {
            Console.WriteLine("not equal");
        }
    }
}

public class MyDataClass {
    private int x = 5;

    public static bool operator ==(MyDataClass a, MyDataClass b) {
        return a.x == b.x;
    }

    public static bool operator !=(MyDataClass a, MyDataClass b) {
        return !(a == b);
    }
}
+5
source share
2 answers

, . == , ==. , object.Equals(x,y) ( x.Equals(y), , null), .

+5

, Equals ==:

http://msdn.microsoft.com/en-us/library/ms173147(VS.80).aspx

( , Equals()):

public static bool operator ==(MyDataClass a, MyDataClass b)
{
    // If both are null, or both are same instance, return true.
    if (System.Object.ReferenceEquals(a, b))
    {
       return true;
    }

    // If one is null, but not both, return false.
    if (((object)a == null) || ((object)b == null))
    {
       return false;
    }

    // Otherwise use equals
    return a.Equals(b);
}

public override bool Equals(System.Object obj)
{
    // If parameter is null return false.
    if (obj == null)
    {
        return false;
    }

    // If parameter cannot be cast to MyDataClass return false.
    MyDataClass p = obj as MyDataClass;
    if ((System.Object)p == null)
    {
        return false;
    }

    return (x == p.x);
}
+1

All Articles