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
We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.
By overriding the toString( ) method, we are customizing the string representation of the object rather than just printing the default implementation. We can get our desired output depending on the implementation, and the object values can be returned.
11.6 The toString methodThe definition does not have the keyword static , because it is not a static method. It is an instance method, so called because when you invoke it, you invoke it on an instance of the class ( Time in this case).
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().
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With