Why and How to Override ToString() Method in C#

Introduction

Have you ever wondered why the following methods are seen on every kind of object you create in your application?

We know that all objects created in .NET inherit from the “System.Object” class. Let's inspect the Object class to find an answer to our question. The following  is what the Object class has.

Look for the public and non-static methods since they will be inherited by child class objects.

You will see Equals(), GetHashCode(), GetType() and ToString() public methods that will be inherited by all the child elements of the “Object” class. That means literally every object in .NET.

ToString() Method in C#

In C#, the ToString() method is used to convert an object to its string representation. It's a part of the base System.Object class and returns the object's type name by default. This method can be overridden in custom classes to provide a meaningful string representation based on object properties. It's commonly used for debugging and displaying object information in a human-readable format.

Why override the ToString() method?

Example

int k = 5;  
Console.WriteLine("This is " + k.ToString());

k.ToString() gives a string representation of 5 and the output will be.

Pretty obvious, right?Assume you have a class named Employee as shown below.

public class Employee  
{  
    public string FirstName   
    {  
        get;  
        set;  
    }  
    public string LastName   
    {  
        get;  
        set;  
    }  
    public int EmployeeID   
    {  
        get;  
        set;  
    }  
    public string Sex   
    {  
        get;  
        set;  
    }  
    public string deptID   
    {  
        get;  
        set;  
    }  
    public string locID  
    {  
        get;  
        set;  
    }  
} 

What do you expect to happen when you call the ToString() method on an Object of class Employee?

What you get is an instance type. We already have a method to get the type of the Object GetType() that the Object class has provided and ToString() is doing the exact same thing but that will not help. This is the reason we should override ToString() to provide our own implementation.

How to Override ToString() method?

What you get is an instance type. We already have a method to get the type of the Object GetType() that the Object class has provided and ToString() is doing the exact same thing but that will not help. This is the reason we should override ToString() to provide our own implementation. The “Virtual” key on the ToString() method allows any child class to re-implement the method as applicable. Let's override the virtual method provided by the “Object” class to make EmployeeObject.ToString() more meaningful.

The preceding screenshot clearly shows the advantage of overriding the ToString() method.

Similarly, Equals() and GetHashCode() should be overridden to make them appropriate to the context of the object.

Happy Coding.


Similar Articles