Thursday, November 30, 2017

Override 'Equals(object obj)' Function in a class (c# / .NET)


Lets suppose 'MyClass' is the name of class for which you want to override 'Equals(object obj)' function. In order to override this function, we also need to override 'GetHashCode()' function. For further information you can check the links below :

https://msdn.microsoft.com/en-us/library/system.object.gethashcode(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.object.equals(v=vs.110).aspx
https://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overridden


You can override the function as below.

public class MyClass
    {

        // This function will override the Equals(arg) function when called for MyClass Object.
        public override bool Equals(object obj)
        {

            bool yourReturnBoolean = base.Equals(obj); // write your logic to define this boolean value here.

            return yourReturnBoolean;
        }

        // This function will override the GetHashCode() function
        public override int GetHashCode()
        {
            return base.GetHashCode(); // logic to calculate the hash code
        }
       
    }


Now let's create an object for the class and call 'Equals(object obj)' function.

MyClass obj = new MyClass();           
bool booleanResult = obj.Equals(destinationObject);


Try it yourself and see the result.

No comments:

Post a Comment