#662 – Overriding the ToString Method for a Custom Type

Every type inherits a ToString method, since every type inherits, directly or indirectly, from System.Object.  For a custom type, this method will by default just display the name of the type.

Dog kirby = new Dog("Kirby", 13);

Console.WriteLine(kirby.ToString());

You can, however, override the ToString method in your class so that it provides information about the specific instance of the class.  In the example below, we override Dog.ToString.

    public class Dog
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public override string ToString()
        {
            return string.Format("Dog [{0}] is {1} years old", Name, Age);
        }
    }

Advertisements