- “.NET interview questions” is the content.
- “o” is the reference to that content.
“==” compares if the object references are same while “.Equals()” compares if the contents are same.
So if you run the below code both “==” and “.Equals()” returns true because content as well as references are same.
object o = ".NET Interview questions"; object o1 = o; Console.WriteLine(o == o1); Console.WriteLine(o.Equals(o1)); Console.ReadLine(); -----------
Now consider the below code where we have same content but they point towards different instances. So if you run the below code both “==” will return false and “.Equals()” will return true.
object o = ".NET Interview questions"; object o1 = new string(".NET Interview questions".ToCharArray()); Console.WriteLine(o == o1); Console.WriteLine(o.Equals(o1)); Console.ReadLine(); Now let's see one more example that shows that the Equals() method is an extension method of the string class when you assign a null value to the string variable and using that variable the Equals() method then gets an exception of a null reference so you must be sure that your variable doesn’t have null values when calling the Equals() method. When your one variable contains a null value then you should use that variable as an argument for the Equals() method. myName.Equals(name); // Throws NullReference exception if myName is Null. The rule of thumb is that for nearly all reference types, use Equals when you want to test the equality rather than reference identity. The exception is for strings; comparing strings with == does make things much simpler and more readable but you need to remember that both sides of the operator must be expressions of type string for the comparison to work properly.