Override ToString() Method in C#

We know that all objects created in .NET inherit from the “System.Object” class.

Let us say when we create a class and if we see the object of the class there are four methods present in each object. These are are GetType(), ToString(), GethashCode(), Equals().

When we call ToString() on any object, it returns to us the Namespace and type name of the class.

This is the default implementation of ToString() provided System.Object class gives us complete type name of the class.

Let us see the code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OverrideTostring  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             Employee emp = new Employee() { EmpId=100, EmpName="Pradeep", DeptName="Computer Science"};  
  13.   
  14.             Console.WriteLine(emp.ToString());  
  15.             Console.ReadLine();  
  16.   
  17.         }  
  18.     }  
  19.   
  20.     public class Employee  
  21.     {  
  22.         public int EmpId { getset; }  
  23.         public string  EmpName { getset; }  
  24.         public string DeptName { getset; }  
  25.   
  26.          
  27.     }  
  28. }  

Output

Let's say we want employee record to display as employee Id, Employee Name, Department Name and each of these fields separated with some space when we are calling ToString() on the employee object.

This string representation of the object we can define in one place in the employee class, and this can be used in multiple places wherever we need it.

Code to override ToString()
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OverrideTostring  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             Employee emp = new Employee() { EmpId=100, EmpName="Pradeep", DeptName="Computer Science"};  
  13.   
  14.             Console.WriteLine(emp.ToString());  
  15.             Console.ReadLine();  
  16.   
  17.         }  
  18.     }  
  19.   
  20.     public class Employee  
  21.     {  
  22.         public int EmpId { getset; }  
  23.         public string  EmpName { getset; }  
  24.         public string DeptName { getset; }  
  25.   
  26.         public override string ToString()  
  27.         {  
  28.             return this.EmpId + " " + this.EmpName + " " +this.DeptName;  
  29.         }  
  30.     }  
  31. }  

Output

 
We saw how to override ToString() and the purpose of doing overriding. Thanks for reading.