Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why returning false ? new Person("james") == new Person("james")?

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;
    }
}
like image 355
Freshblood Avatar asked Aug 03 '10 11:08

Freshblood


1 Answers

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.

like image 73
dtb Avatar answered Sep 20 '22 03:09

dtb