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

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

Why to Override

Given this code:

  1. int k = 5;  
  2. 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.
  1. public class Employee  
  2. {  
  3.     public string FirstName   
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string LastName   
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public int EmployeeID   
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public string Sex   
  19.     {  
  20.         get;  
  21.         set;  
  22.     }  
  23.     public string deptID   
  24.     {  
  25.         get;  
  26.         set;  
  27.     }  
  28.     public string locID  
  29.     {  
  30.         get;  
  31.         set;  
  32.     }  
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

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.

Up Next
    Ebook Download
    View all
    Learn
    View all