Determine object equivalence in C#

Imagine a simple class, which does nothing except being simple:


class Foo
{
    public String Name { get; set; }

    public Foo(String name)
    {
        this.Name = name;
    }
}

If the two classes are created with same Name (e.g. Olli), how can I determine that these are obviously the same objects.
The == operator, as normally is for comparison, returns false, because it compares the memory position of the object, not the content.

static void Main(string[] args)
{
    Foo foo1 = new Foo("Olli");
    Foo foo2 = new Foo("Olli");

    bool areEqual = (foo1 == foo2); // false

    Console.WriteLine(areEqual);
    Console.ReadLine();
}

The solution is to overload the operator and to compare the property name of two objects.

class Foo
{
    public String Name { get; set; }

    public Foo(String name)
    {
        this.Name = name;
    }

    public static Boolean operator ==(Foo f1, Foo f2)
    {
        return f1.Name == f2.Name;
    }

    public static Boolean operator !=(Foo f1, Foo f2)
    {
        return f1.Name != f2.Name;
    }
}

Now, the result of the comparison is true.

Advertisements
This entry was posted in C#, Development and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s