Compare two objects

Employee emp1 = new Employee {Name = "Swapnil",Age = 27 }; Employee emp2 = new Employee { Name = "Swapnil", Age = 27 }; if (object.Equals(emp1, emp2)) { } else { } 

This code cannot compare. How can I compare two s objects in C #?

+4
source share
3 answers

Without overriding the Equals method, only a comparative comparison will be performed. You want to perform a comparison of values.

Override the method in your Employee class as follows:

 public override bool Equals(Object emp) { // If parameter is null return false. if (emp == null) { return false; } // If parameter cannot be cast to Point return false. Employee e = emp as Employee; if ((System.Object)e == null) { return false; } // Return true if the fields match return (Name == emp.Name) && (Age == emp.Age); } 

Then compare the objects as follows:

 if(emp1.Equals(emp2)) { ... } 

OR with a comparison operator:

 if(emp1 == emp2) { ... } 

Read more about MSDN here: http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx

+2
source

You need to override Equals in your Employee class. Example (stolen and modified from MSDN ):

  public override bool Equals(Object obj) { // Check for null values and compare run-time types. if (obj == null || GetType() != obj.GetType()) return false; Employee e = (Employee)obj; return (this.Name == e.Name) && (this.Age == e.Age); } 

and then use it like this:

 if (emp1.Equals(emp2)) { // ... 

Note. If you override Equals() , you must also override GetHashCode() .

0
source

Check this link for a description of Object.Equals.

If you leave your class as it is, then the comparison will be a comparison of the links. This is not what you want, you want to check for equality based on your properties.

If you override the Equals (object) method in your Employee class, you can implement your own equal test there. See here , as Botz3000 has already said, on how to override this method and implement your own test.

0
source

All Articles