Implement the Equals method - CSharp Custom Type

CSharp examples for Custom Type:Method

Description

Implement the Equals method

Demo Code

using System;//from w ww .  j  ava  2  s  . com
class Dog
{
    private string name;
    public Dog()
    {
        name = "unknown";
    }
    public Dog(string initialName)
    {
        name = initialName;
    }
    public string Name
    {
        get
        {
            return name;
        }
    }
    public override string ToString()
    {
        return "Dog name: " + name;
    }
    public override bool Equals(object obj)
    {
        Dog tempDog = (Dog)obj;
        if (tempDog.Name == name)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
class ObjectTester
{
    public static void Main()
    {
        Dog myDog = new Dog("Fido");
        Dog yourDog = new Dog("Fido");
        Console.WriteLine(myDog);
        if (myDog.Equals(yourDog))
            Console.WriteLine("myDog has the same name as yourDog");
        else
            Console.WriteLine("myDog and yourDog have different names");
    }
}

Related Tutorials