Program to Override the ToString() method of Object class in Child class using C#

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 1258
Let us say we have a class by the name Employee.cs whith some properties and we want to override the ToString() method of Object class in the Employee class. The below program will do so.

using System;

public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string Gender { get; set; }
public string PhoneNumber { get; set; }
public string Email { get; set; }
public string Address { get; set; }

public override string ToString()
{
string strEmployeeRecords = $"EmployeeId: {EmployeeId}";
strEmployeeRecords += $", EmployeeName: {EmployeeName}";
strEmployeeRecords += $", Gender: {Gender}";
strEmployeeRecords += $", PhoneNumber: {PhoneNumber}";
strEmployeeRecords += $", Email: {Email}";
strEmployeeRecords += $", Address: {Address}";
return String.Format(strEmployeeRecords);
}
}

Comments or Responses

Posted by: Vishalneeraj-24503 on: 1/13/2016 Level:Platinum | Status: [Member] [MVP] | Points: 10
Hi,

Have you tested this. There is an error. I copied all the code.
Kindly let me know how to test and what is the purpose of overriding tostring() method.
Posted by: Rajnilari2015 on: 1/13/2016 Level:Platinum | Status: [Member] [Microsoft_MVP] [MVP] | Points: 10
@Vishalneeraj-24503 Sir, yes the program has been tested in VS 2015 because it is using string interpolation and the purpose of this program is described here http://www.dotnetfunda.com/articles/show/3229/reading-excel-and-csv-file-using-linqtoexcel

Kindly let me know how I may help you further.

Thanks

Login to post response