#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

%d bloggers like this: