Wednesday, January 1, 2014

Difference Between == and .Equal()

For Value Type: For Value type their result is same.Both (==and .Equal) compare objects by value. Most of the value types provided by the framework provide their own overload for ==.

For Example:

int a = 20;
int b = 20;

Console.WriteLine( a == b);
Console.WriteLine(a.Equals(b));

Output:
True
True

For Reference Type: For reference type they behave differently

== Perform an Identity comparison,i.e. it will return true if two references refer to the same object.While Equals() method is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent.

For Example:

StringBuilder a1 = new StringBuilder(“Khaleek”);
StringBuilder a2 = new StringBuilder(“Khaleek”);

Console.WriteLine(a1 == a2);
Console.WriteLine(a1.Equals(a2));

Output:
False
True

In above example, a1 and a2 are different objects hence “==” returns false, but they are equivalent hence “Equals()” method returns true. Remember there is an exception of this rule, i.e. when you use “==” operator with string class it compares value rather than identity.

Because == is overloaded for String Types.
When to use “==” operator and when to use “.Equals()” method?
For value comparison, with Value Type use “==” operator and use “Equals()” method while performing value comparison with Reference Type.

No comments:

Followers

Link