I have override GetHashCode
and Equals
and both methods provide same results for different objects but why still getting false ?
class Program
{
static void Main(string[] args)
{
Console.WriteLine(new Person("james") == new Person("james"));
Console.ReadKey();
}
}
class Person
{
private string Name;
public Person(string name)
{
Name = name;
}
public override int GetHashCode()
{
return 1;
}
public override bool Equals(object obj)
{
return true;
}
}
Because the ==
operator defaults to reference equality. It doesn't call your Equals
method.
You can override the ==
operator if you want. See: Guidelines for Overriding Equals() and Operator ==
In C#, there are two different kinds of equality: reference equality (also known as identity) and value equality. Value equality is the generally understood meaning of equality: it means that two objects contain the same values. For example, two integers with the value of 2 have value equality. Reference equality means that there are not two objects to compare. Instead, there are two object references and both of them refer to the same object.
[...]
By default, the operator == tests for reference equality by determining whether two references indicate the same object. Therefore, reference types do not have to implement operator == in order to gain this functionality. When a type is immutable, that is, the data that is contained in the instance cannot be changed, overloading operator == to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. It is not a good idea to override operator == in non-immutable types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With