I want to override the Tostring() method for changing some characters. Is it possible? If yes, How can I do this?
6 Answers
In your class where you want to override it in, add:
public override string ToString()
{
// return your string representation
}
- 11,848
- 1
- 33
- 56
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.
- 767,688
- 176
- 1,542
- 1,434
Add the following in the class you want to override the ToString function:
public override string ToString()
{
// Add your implementation here
}
- 24,988
- 41
- 129
- 201
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
}
- 30,030
- 21
- 100
- 124
- 11,776
- 15
- 68
- 97
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():
JSON serialization (either DataContractJsonSerializer, JSON.NET or the NuGet package JsonValue).
XmlSerialize
ServiceStack.Text C# .NET Extension method: T.Dump();
- 30,030
- 21
- 100
- 124
- 23,917
- 16
- 136
- 163