Below is the sample code that i am trying out:
namespace ConsoleApplication9
{
class Program
{
public class MyBaseClass
{
public string name = "";
}
static void Main(string[] args)
{
MyBaseClass mybase = new MyBaseClass();
mybase.name = "n";
MyBaseClass mybase2 = new MyBaseClass();
mybase2.name = "n";
Console.WriteLine("comparison using == {0}", mybase == mybase2); // prints false, which i understand both object's references are not same
Console.WriteLine("Comparions using Equasl {0}", mybase.Equals(mybase2)); // prints False again , Why ??
Console.ReadKey();
}
}
}
Now my understanding is that == operator compares the reference of two objects while .Equals checks if the content is same or not. If .Equals checks that the content is same or not, why mybase.Equals(mybase2) prints False for me. Both objects mybase and mybase2 have the same content.
Edit1:
Question1: Based on some of the responses and comments that by default .Equals checks for references unless overridden, I would like to understand why "==" and ".Equals" prints different results for following code:
object string1 = new string(new char[] { 't', 'e', 's', 't' });
object string2 = new string(new char[] { 't', 'e', 's', 't' });
Console.WriteLine(string1==string2); // prints false
Console.WriteLine(string1.Equals(string2)); // prints true
Here both string1 and string2 are independently created, as such my understanding is since "==" checks for references it is printing false, but why ".Equals" prints true if ".Equals" default behavior is that it also checks for references??
Question2: Also for the following code :
string a = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });
string b = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });
Console.WriteLine(a == b); //prints true
Console.WriteLine(a.Equals(b)); // prints true
why both "==" and ".Equals" prints true. Are these two strings not completely different in C# ??