Saturday, December 31, 2011

Difference between Equal method and Equal to operator (==))

Equality comparison in C# is of two different kinds:-

1)       Value equality and
2)       reference equality

1) Value equality normally compares two objects by value.  

For ex:-

val1 and val2 are two integer variables having equal value as 10.

int val1 = 10;
int val2 = 10;
Console.WriteLine(val1.Equals(val2));
Console.WriteLine(val1 == val2);
Console.ReadLine();

Output
--------
True
True

Because the value equality is based on object values, the Output using the Equal method and Equal operator (==) is True.

2) Reference equality compares two objects by reference and not by value.

If there are two objects obj1 and obj2 which are referring to the obj3, then the reference equality will return true.

For ex:-

I have create a sample class
public class Test
{
   public Test()
   { }
}

Herein creating an object of Test class.
Test objTest = new Test();

Example 1:-

Now two different objects objT and objT1 is created which are referring to the objTest object.
Object objT = objTest;
Object objT1 = objTest;

Console.WriteLine(objT.Equals(objT1));
Console.WriteLine(objT == objT1);
Console.ReadLine();

Output
--------
True
True

Example 2:-

In this example, two different objects objT and objT1 are created of the Test class.

Object objOne = new Test();
Object objTwo = new Test();

Console.WriteLine(objOne.Equals(objTwo));
Console.WriteLine(objOne == objTwo);

Output
--------
False
False

objOne and objTwo are two objects of the same class Test but they are not pointing or referring to the same object, that’s the reason the reference equality will return False for reference comparison.


Happy Coding.......

No comments :

Post a Comment