Skip to content

How To Override ToString() in a Simple C# Class

Updated: at 02:12 PM

So, you have a simple class that has a bunch public properties and you want to be able to use ToString() on it to show some data?  It’s easy.  All you have to do is override the ToString() class inside your C# code.

So, here is an example class that does that.

public class DbProgressReport
public string ScopeNameProgress { get; set; }
public string SourceOrDestination { get; set; }
public string TableName { get; set; }
public int TotalRecords { get; set; }
public int ChangesApplied { get; set; }
public int ChangesFailed { get; set; }
public int ChangesPending { get; set; }
public int Deletes { get; set; }
public int Inserts { get; set; }
public int TotalChanges { get; set; }
public int Updates { get; set; }
public DateTime LastChangeDate { get; set; }

public override string ToString()
string readableDbProgressReport =
"{0} ScopeName {1},Table {2},TotalRecords {3}"
SourceOrDestination, ScopeNameProgress, TableName);

return readableDbProgressReport;

Now, all you have to do when accessing this class is use the ToString property.

That is:

DbProgressReport dbProgressReport = 
new DbProgressReport("source","scopename","tablename");
string str = dbProgressReport.ToString();

and the output will be:

source ScopeName scopename,  Table tablename

Simple as that!

Hope this helps.

Check out the ORM (Object Relational Mapper) PRISMA. The database access method I use in all my projects