In this article, we will learn the difference between == operator and .Equals() method In C#.
In general, both == operator and .Equals() method in C# are used to compare objects to check equality but here are some of the differences:
- The main difference between == operator and .Equals() method is that one is an operator and the other is a method.
- We can use == operators for reference/address comparison and .Equals() method for content comparison. In simple terms, == checks if both objects point to the same memory location whereas .Equals() evaluates to the comparison of values in the objects.
Example-1
static void Main(string[] args) { object obj1 = "Hello World!"; object obj2 = obj1; Console.WriteLine(obj1 == obj2); Console.WriteLine(obj1.Equals(obj2)); }
Here we are creating two objects namely obj1 and obj2. Where obj1 is a simple object and passing obj1 as a reference to obj2.
What will happen internally is both obj1 and obj2 have the same content and also point towards the same reference. If we do == operator comparison or .Equals() method comparison, it should give the same result for both of them.
Output
Example-2
static void Main(string[] args) { object obj1 = "Hello World!"; object obj2 = new string("Hello World!"); Console.WriteLine(obj1 == obj2); Console.WriteLine(obj1.Equals(obj2)); }
In this example, obj1 is pointing towards the “Hello World!” content. And obj2 is pointing towards the same content but it is a fresh object.
If we do == operator comparison it should return the False and .Equals() method comparison will return the True result because the content is the same but object references are different.
Output
Also, check How To Create Foreign Key In Code First Approach