tags:

views:

358

answers:

6

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

+13  A: 

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

public override string ToString()
{
  // return your string representation
}
Wim Hollebrandse
I do feel somewhat embarrassed to gain rep over this...
Wim Hollebrandse
You beat me with 15seconds! ;-)
stiank81
+1 yeh, I was beaten by 18 secs
Asad Butt
Well - the answer is short and precise. Don't feel embarrassed that you now even got the Nice Answer badge for it! :-)
stiank81
It's all about quick draw posting ... you still get +1 as the answer is good! :-)
WestDiscGolf
6 upvotes on the question already, not *that's* embarrassing.
Hans Passant
+1  A: 

Check this link: http://msdn.microsoft.com/en-us/library/ms173154(VS.80).aspx

Mark B
+5  A: 

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

public override string ToString()
{
    // Add your implementation here
}
stiank81
+3  A: 

See example at MSDN.

public override String ToString() 
{
    return String.Format("Test {0}", 101);
}
p2u
+4  A: 

All you need is to try to write public ovverride then Visual Studio will create the method for you like this

 public override string ToString() 
 { 
      // implement your own code and return desiered string
 } 
Nasser Hadjloo
+11  A: 

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
+1 for being able to read *that* much (and clearly correct) into OP's question.
Wim Hollebrandse