8

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
masoud ramezani
  • 22,228
  • 29
  • 98
  • 151

6 Answers6

16

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

public override string ToString()
{
  // return your string representation
}
Wim
  • 11,998
  • 1
  • 34
  • 57
15

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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
5

Add the following in the class you want to override the ToString function:

public override string ToString()
{
    // Add your implementation here
}
stiank81
  • 25,418
  • 43
  • 131
  • 202
3

See example at MSDN.

public override String ToString() 
{
    return String.Format("Test {0}", 101);
}
p2u
  • 300
  • 1
  • 9
3

All you need is to try to write public override, and then Visual Studio will create the method for you like this:

 public override string ToString()
 {
      // Implement your own code and return desired string
 }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nasser Hadjloo
  • 12,312
  • 15
  • 69
  • 100
0

If someone looks for a general answer to "How to override the ToString() method", I've written a post, "Override ToString() using JSON serialization or something else."

In a summary, the following technologies can be used to simplify creation of ToString():

  1. JSON serialization (either DataContractJsonSerializer, JSON.NET or the NuGet package JsonValue).

  2. XmlSerialize

  3. LINQPad's dump an arbitrary object to an HTML string

  4. ServiceStack.Text C# .NET Extension method: T.Dump();

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170