views:

1524

answers:

3

Howdy,

I have a public static class in which I would like to have a ToString() method.

I have defined it as public static string ToString(), but get the following warning:

'Class.ToString()' hides inherited member 'object.ToString()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.

If I add the override keyword I get this error instead:

A static member 'Class.ToString()' cannot be marked as override, virtual, or abstract

How do I get rid of that warning and let my static class have the ToString() method.

Thank you,
Keith

+2  A: 

Ok, so in asking the question, I found an answer:

The new Modifier:

http://msdn.microsoft.com/en-us/library/51y09td4(VS.71).aspx#vclrfnew_newmodifier

here is the method now:

public new static string ToString()

Thank you, Keith

Keith Sirmons
+4  A: 

In a static class you cannot override ToString. .ToString is an instance method and by definition a static class can only have static members.

Also why would you want to override .ToString()? There is no way to get an instance of the class and hence no way to call the function.

Note: Using the new syntax will not override .ToString. It will create a new member that is completely unrelated to the Object.ToString() method.

JaredPar
Strictly speaking, he's not overriding object.ToString, he's hiding it. I can't speak as to why...
Bill the Lizard
Correct. The title of his post though says "override" so I wanted to clarify what that actually meant compared with my answer.
JaredPar
+7  A: 

Yes, using the "new" modifier will effectively silence the compiler warning but you are explicitly hiding an instance method with a static method. (This is different than overriding the method.) Typically you don't want to hide an instance method except with very good reasons and you really shouldn't hide it with a static method as that really changes the behavior semantics of the call. Every object in .NET has an instance method named ToString() that has specific behavior that developers expect; by hiding that behavior with a new static method you are changing that expectation which can lead to a lot of confusion.

What are you "to stringing"? Static classes typically don't hold internal state so there really shouldn't be any internal data to provide as the logical output of a ToString() call. You may want to rethink your class design or provide a different method name that more clearly indicates the purpose of the method without hiding the instance ToString().

Scott Dorman