What is the difference between == and Equals?

 Posted by Ddd on 1/22/2011 | Category: C# Interview questions | Views: 2784 | Points: 40
Answer:

Both are used for comparison of variables, can be overloaded and return a Boolean value.

The differences are:-

Consider two variables of different types:
1) int a = 20;
string b = "20";

//Compiler error (== cannot be applied to int and string)
Console.WriteLine(a == b);

//output: False
Console.WriteLine(a.Equals(b));

2)int c = 455;
long f = 455;
//True
Console.WriteLine(c == f);
//False
Console.WriteLine(c.Equals(f));

//Equals strictly checks that 2 variables should be of the same type

// == gives True if 2 variables ' data types allow for similar values(Example: int and long)

3)List<string> y = new List<string>();
y.Add("one");
List<string> z = new List<string>();
z.Add("one");
Console.WriteLine(y == z);
Console.WriteLine(y.Equals(z));

Both will give False.


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response