How to check object equality in .net?
Hello to all,
Suppose there are two object like obj1 and obj2, which is defined as the System.Object. It can be of any type like String, Int32, Double,Boolean, etc. In this case how can I check that obj1 and obj2 are equal or both have the same type & value. Can anyone tell me how to check object equality in .net? Please help me.
Thank you.
Re: How to check object equality in .net?
You have to use object.Equals() method in your code to check whether two object are equal or not in the following ways.
Code:
object.Equals(obj1, obj2)
There is no need to use == to do this, because this operator are not applied polymorphically. When you use == , then it means that you are tried to override something.
Re: How to check object equality in .net?
When you use == operator to check for object equality, objects are compare by reference and when you use Equals methods to check for object equality, objects are compare by value. Just use this example for understanding.
Code:
StringBuilder ss1 = new StringBuilder(“Yess”);
StringBuilder ss2 = new StringBuilder(“Yess”);
Console.WriteLine(ss1 == ss2);
Console.WriteLine(ss1.Equals(ss2));
Re: How to check object equality in .net?
You have to use Equals method when you work on strings and the value types you listed. If you use "==" for following code then your program will give error message, because references to the boxed objects are not equal.
Code:
int a = 1;
int s = 1;
Object obj1 = a;
Object obj2 = s;
To fix this problem you have to use following code:
Code:
Console.WriteLine(ss1 == ss2);
Re: How to check object equality in .net?
You can check object equality in .net using two methods. First using "==" operator and other is Equal method. If you want to test 2 objects which are of two types then you have to cast them to an object. When you use "==", operator overloading work at compile time. In this case we are dealing with System.Object.
Re: How to check object equality in .net?
If you want to compare two object then you have to use "object.Equals(obj1, obj2)" in your code. It is one of the simplest way to do this. I have written simple program for you. Just try to understand it.
Code:
public class SomethingEg {
public long Ids { get; set; }
public string Names { get; set; }
public override bool Equals(object objs) {
if (objs == null)
return false;
if (((Somethings)objs) == nulls)
return false;
Somethings ss = (Somethings)obj;
return this.Ids == ss.Ids && string.Equals(thiss.Names, ss.Names);
}
public bool Equalss(Something ss) {
if (ss == null)
return false;
return this.Ids == ss.Id && string.Equals(thiss.Namess, ss.Names);
}
}