Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override the ToString() method in C#?

Tags:

c#

overriding

I want to override the Tostring() method for changing some characters. Is it possible? If yes, How can I do this?

like image 231
masoud ramezani Avatar asked Feb 23 '10 11:02

masoud ramezani


2 Answers

In your class where you want to override it in, add:

public override string ToString()
{
  // return your string representation
}
like image 64
Wim Avatar answered Sep 17 '22 15:09

Wim


As per your question, to change some characters in the ToString implementation, you need to call the existing ToString method by using the base keyword:

public override string ToString()
{
    return base.ToString().Replace("something", "another thing");
}

Note that if you forget the base keyword it will call itself repeatedly until you get a StackOverflowException.

like image 22
Mark Byers Avatar answered Sep 20 '22 15:09

Mark Byers