Alex Rivera | Logout

C#: public new string ToString() VS public override string ToString()

Asked 2009-06-18T19:57:58.530
21

I want to redefine the ToString() function in one of my classes.

I wrote

public string ToString()

... and it's working fine. But ReSharper is telling me to change this to either

public new string ToString() 

or

public override string ToString()

What's the difference? Why does C# requires something like this?

Edit
Report

1 Answer

36

If you use public string ToString() it is unclear what you intended to do. If you mean to change the behaviour of ToString via polymorphism, then override. You could add a new ToString(), but that would be silly. Don't do that!

The difference is what happens when you do:

MyType t = new MyType();
object o = t;
Console.WriteLine(t.ToString());
Console.WriteLine(o.ToString());

If you override, both will output your new version. If you new, only the first will use your new version; the second will use the original implementation.

I don't think I've ever seen anybody use method hiding (aka new) on ToString().

answered 2009-06-18T20:01:19.833

Your Answer