Tuesday, 12 May 2020

C# Equal vs "==" output related : What will be output of following code ?

Question related to  Equal vs "=="

Normally (when not dealing with strings), 
Equals compares values, while == compares object references

What will be output of following C# code ?
Que
    Object obj1 = 10;
    Object obj2 = obj1;
    Console.WriteLine($"obj1 == obj2        : {obj1 == obj2}");
    Console.WriteLine($"obj1.Equals(obj2)   : {obj1.Equals(obj2)}");
         

Output
    obj1 == obj2        : True
    obj1.Equals(obj2)   : True

Note If two objects we are comparing are referring to the same exact instance of an object, then both Equal  & "==" will return true,

If both has the same content but came from a different source (is a separate instance with the same data), only Equals will return true.

Que
    Object obj1 = 10;
    Object obj2 = obj1;
    Console.WriteLine($"obj1.Equals(obj2)   : {obj1.Equals(obj2)}");
    Console.WriteLine($"obj1 == obj2        : {obj1 == obj2}");
Output
    
    obj1 == obj2 : False
    obj1.Equals(obj2) : True

Que : 

    Object obj1 = 10;
    Object count1 = 10;
    Console.WriteLine($"obj1.Equals(count1) : {obj1.Equals(count1)}");

Output
    obj1.Equals(count1) : True