ToString() or not ToString()

In general, I try to avoid using .ToString() as much as possible. Instead I prefer to just rely on the automatic string conversion that is done in string concatenations, or in the string.Format() methods.

Consider the simple code example below.

public class Program
{
    static void Main(string[] args)
    {
        Car car = GetCar();

        Console.WriteLine(car.ToString());
        Console.WriteLine(car + string.Empty);
        Console.WriteLine(string.Format("{0}", car));

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    public static Car GetCar()
    {
        return new Car { Make = "Toyota", Model = "Aurion", Colour = "Brown" };
    }
}

public class Car
{
    public string Make { get; set; }
    public string Model { get; set; }
    public string Colour { get; set; }

    public override string ToString()
    {
        return string.Format("{0} {1} {2}", Colour, Make, Model);
    }
}

All three Console.WriteLine outputs show the same results.

BrownToyotaAurionOutput

So why avoid .ToString()? Because of NullReferenceException.

If we update line 17 to return a null value,

        return null;

line 7 will start throwing a NullReferenceException, while lines 8 & 9 will still work fine, outputting an empty string because the automatic conversion checks for and handles null values.

You could always put exception handling around your code and always check for null objects before calling .ToString(), but that’s a lot of hassle just trying to stringify an object. And from experience, hardly anyone checks if an object is null before calling .ToString().

So making a habit of avoiding .ToString() and using alternatives like string concatenation, string.Format() or even a StringBuilder will make your code more robust by preventing unexpected NullReferenceExceptions.

There are exceptions to this, such as when you know the object is a non-Nullable object. Most common cases for this are with the builtin numeric objects (int, long, float…) and DateTime objects, because they have very handy .ToString(string format) methods for formatting its string output.

Advertisements

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