tags:

views:

1929

answers:

7

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?

+9  A: 

The problem is that ToString is a virtual method. In order to override a virtual method in C# you need to specify the override keyword.

You almost certainly do not want the "new" version. .

JaredPar
+2  A: 

You want to override. There's really no advantage to hiding in your case (using "new").

Here's an article on the differences between overriding and hiding.

Jon B
A: 

C# doesn't require it; Resharper does. It requires it because the two keywords represent significantly different behavior, and if you don't specify, someone reading your code might not be entirely clear on which the default behavior is (it's new.)

In this case you clearly want to override.

mquander
Actually, even without R# you'll get a warning about this. The *language* doesn't demand it, but even the "express" (free) IDE knows it is a bad idea.
Marc Gravell
Another reason why I like "Treat warnings as errors"
Wayne
+18  A: 

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().

Marc Gravell
Nice code example. I was working on something similar.
RichardOD
thanks, very clear and helpful
marcgg
Unfortunately I have seen several examples of method hiding in C#. None of them were pretty.
JaredPar
Oh sure, method hiding isn't *that* uncommon - I've just never seen it on ToString() ;-p But DbConnection.CreateCommand is a classic example in the wider context...
Marc Gravell
Wow - why on earth would anyone downvote this?
Jon Skeet
A: 

What you do all depends on the behaviour you want. This article explains how the behaviour of ToString works depending on how you defined the method and what level in a class hierarchy you call ToString on.

RichardOD
+2  A: 

The new modifier will hide or "shadow" the member with the same signature in the base class where as overriding provides a new implementation of a member inherited from a base class. Here is a good article on the differences between shadowing and overriding.

JP Alioto
A: 

A personal recommendation from me would be to not use hiding; it causes many ambiguities and solves few.