If it wasn't a virtual method, you can still achieve the same effect by just writing your ToString method normally, right?
You could even use the optional new keyword.
Wouldn't this have better performance?
If it wasn't a virtual method, you can still achieve the same effect by just writing your ToString method normally, right?
You could even use the optional new keyword.
Wouldn't this have better performance?
If it wasn't a virtual method, you can still achieve the same effect, by just writing your ToString method as normal, right?
No. Consider (e.g.) the signature of (one overload of) the Console.WriteLine function:
void Console.WriteLine(object o);
If ToString were novirtual, this would always call the System.Object.ToString implementation, not the one on the actual object passed to the function.
Along the lines of Konrad's comment:
public Class A
{
public new string ToString()
{
return "Hello from A";
}
}
object a = new A();
a.ToString();
Would NOT return 'Hello from A' but instead would return the type name (which is what object's implementation does).
You could ask the same of any virtual method.
So this question is basically the same as asking "What is the purpose of virtual methods?"