Overriding the ToString() Method in C#

String Operations

Sometimes it can be useful to override a method, be it your own or maybe even one of .NET’s methods. In this example I am going to create a simple class and then show you how to override its ToString() method.

In .NET, whenever you create a class, the ToString() method is automatically created for you internally. But most of the time it is not useful at all because all it will return is the class name. So to make it more useful we can override it and return our own value instead – for example a string representation of the object.

To start off let’s create a simple class as shown below:

using System;

namespace OverridingMethods
{
    public class Automobile
    {
        #region Private Members
        private string brand;
        private string name;
        private string model;
        private int year;
        private string colour;
        #endregion

        #region Public Properties
        public string Brand
        {
            get { return brand; }
            set { brand = value; }
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string Model
        {
            get { return model; }
            set { model = value; }
        }

        public int Year
        {
            get { return year; }
            set { year = value; }
        }

        public string Colour
        {
            get { return colour; }
            set { colour = value; }
        }
        #endregion

        #region Constructor
        public Automobile(string brand, string name, string model, int year, string colour)
        {
            this.brand = brand;
            this.name = name;
            this.model = model;
            this.year = year;
            this.colour = colour;
        }
        #endregion
    }
}

The class represents an automobile. Now let’s initialise the class and call the ToString() method like this:

Automobile car = new Automobile("Hyundai", "Accent", "CRDi", 2005, "Silver");
MessageBox.Show(car.ToString());

This is the result we get: OverridingMethods.Automobile. Not very useful is it?

So to make the ToString() method of our class more useful let’s override it using the override keyword as shown below:

public override string ToString()
{
    return string.Format("{0} {1} {2} {3} {4}", colour, year, brand, name, model);
}

Now if we call the ToString() method we will get this: Silver 2005 Hyundai Accent CRDi. Now this makes much more sense doesn’t it?

Dave

0 comments… add one

Leave a Comment