Sunday, October 12, 2008

Object.Equals C#

This is one of the basics which every .Net developer has to know. Hence I would like to explain this with a proper example.

Let us consider the following class.

class Employee
{
public Employee(int empID, string name)
{
this.empID = empID;
this.empName = name;
}

private int empID;

public int EmpID
{
get { return empID; }
set { empID = value; }
}
private string empName = string.Empty;

public string EmpName
{
get { return empName; }
set { empName = value; }
}
}

Now if I execute the folowing snippet of code

Employee emp1 = new Employee(1, "Ajeeth");
Employee emp2 = new Employee(1, "Ajeeth");
MessageBox.Show(emp1.Equals(emp2).ToString());
bool eq = (emp1 == emp2);
MessageBox.Show(eq.ToString());

The output would be

False
False

The reason being the Equals and == checks for the references by default. Hence it is necessary to override the Equals method in the Employee class which would now look like.

class Employee
{
public Employee(int empID, string name)
{
this.empID = empID;
this.empName = name;
}

private int empID;

public int EmpID
{
get { return empID; }
set { empID = value; }
}
private string empName = string.Empty;

public string EmpName
{
get { return empName; }
set { empName = value; }
}

public override bool Equals(object obj)
{
if (this.empID == (obj as Employee).empID)
return true;
return false;
}

public override int GetHashCode()
{
return this.empID;
}

public static bool operator ==(Employee emp1, Employee emp2)
{
return emp1.Equals(emp2);
}

public static bool operator !=(Employee emp1, Employee emp2)
{
return !(emp1 == emp2) ;
}

}

If you notice above I am overriding Equals and overloading the operator ‘==’ which internally calls the Employee.Equals() method. If you also see I am comparing the 2 objects of Employee object with their unique fields. This would enforce a value comparison. The C# compiler provides a warning if we forget to override the Object.GetHashCode() method when Object.Equals is overridden. The GetHashCode() should ensure that it returns unique id for 2 different objects of same class. This would impact the performance of HashTables if the objects are stored as Keys.

If you execute the following snippet would be

Employee emp1 = new Employee(1, "Ajeeth");
Employee emp2 = new Employee(1, "Ajeeth");
MessageBox.Show(emp1.Equals(emp2).ToString());
bool eq = (emp1 == emp2);
MessageBox.Show(eq.ToString());

The output would be

True
True

If you execute the following snippet would be

Employee emp1 = new Employee(1, "Ajeeth");
Employee emp2 = new Employee(2, "Aravind");
MessageBox.Show(emp1.Equals(emp2).ToString());
bool eq = (emp1 == emp2);
MessageBox.Show(eq.ToString());

The output would be

False
False

Happy Coding..

No comments: