How overriding Object.ToString() helps

System.Object provides a ToString() method which gives a human readable string about the object. Many people haven’t realized how useful is this tiny method.

Consider the following code:

namespace PersonDetails
{
    class Person
    {
        public Person(string firstName, string lastName, int age)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Age = age;
        }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person chuckNorris = new Person("Chuck", "Norris", 20);
            Console.WriteLine(chuckNorris.ToString()); // Prints PersonDetails.Person
        }
    }
}

The information printed is not at all helpful. Let us override ToString() and see the difference.

public override string ToString()
{
    // Returning a formatted string.
    return string.Format("Name : {0},{1}  Age : {2}", FirstName, LastName, Age);
}

Overriding ToString() is more helpful when you debug the class. Visual studio shows the output of ToString() and it helps to identify the objects easily. Consider the following screen-shots of a quick-watch window showing items in a collection with and without overriding ToString.

View of a collection with objects that have default ToString() implementation

View of a collection with objects that have default ToString() implementation

Quick-watch window showing a collection of objects that have ToString() overidden

Quick-watch window showing a collection of objects that have ToString() overidden

Formatting the output of ToString()

Output of ToString() can be formatted in the way we need. .NET framework provides System.IFormattable interface for extending the behavior of ToString().

Here is the person class after implementing IFormattable.

class Person : IFormattable
{
    public Person(string firstName, string lastName, int age)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Age = age;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public override string ToString()
    {
        return ToString(null);
    }

    public string ToString(string format)
    {
        return ToString(format, null);
    }

    public string ToString(string format, IFormatProvider formatProvider)
    {
        if (string.IsNullOrEmpty(format)) format = "fla";
        if (formatProvider != null)
        {
            // Getting the formatter
            ICustomFormatter formatter = formatProvider.GetFormat(this.GetType())
                as ICustomFormatter;
            if (formatter != null)
                return formatter.Format(format, this, formatProvider);
        }
        switch (format)
        {
            case "fla":
                return string.Format("{0},{1} Age : {2}", this.FirstName, this.LastName, this.Age);
            case "fl":
                return string.Format("{0},{1}", this.FirstName, this.LastName);
            case "lf":
                return string.Format("{0},{1}", this.LastName, this.FirstName);
            default:
                return string.Format("{0},{1} Age : {2}", this.FirstName, this.LastName, this.Age);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person chuckNorris = new Person("Chuck", "Norris", 26);
        Console.WriteLine("{0}", chuckNorris);      // Prints : Chuck,Norris Age : 26
        Console.WriteLine("{0:fl}", chuckNorris);   // Prints : Chuck,Norris
        Console.WriteLine("{0:lf}", chuckNorris);   // Prints : Norris,Chuck
        Console.Read();
    }
}

You can also use chuckNorris.ToString(“fl”). Overriding ToString() is terribly useful and it is recommended to override it whenever possible.

Happy programming!

Advertisements

One thought on “How overriding Object.ToString() helps

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