tags:

views:

174

answers:

3

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?

+13  A: 

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.

Konrad Rudolph
Thanks, if it was a generic method, then it would work, right?
Joan Venge
No it wouldn't. Please consult a tutorial about polymorphism.
Henk Holterman
If it was void Console.WriteLine(T t), I think it would.
Joan Venge
If it were a C++ template it would work. But with a C# or Java generic, the argument would have to implement an interface, which would involve dynamic dispatch much like a virtual method.
Daniel Earwicker
But it would require some constraints on T. Same problem just got more complicated.
Henk Holterman
Why not spend 30 seconds writing a console application?
Daniel Earwicker
I wrote a sample, but there are issues because I can't add my method to show up on T without additional complexity. But if there was a non virtual method there, I could try it out.
Joan Venge
Do you mean, if the language worked differently?
Daniel Earwicker
Yeah like if the Object actually had a GetString method that's non-virtual, then I could try it out. I tried using an extension method, it didn't work. The GetString doesn't show up on T, which requires interface constraints, etc to get this working. Then of course it would defeat the purpose.
Joan Venge
To adapt a German saying: “If we had cheese, we could feast on cheese sandwiches – *if* we had bread”, right? ;-)
Konrad Rudolph
That's pretty good :)
Joan Venge
@Konrad: I hadn't heard that one. Another is, "If we had ham, we could have ham and cheese, if we had cheese".
John Saunders
+4  A: 

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

n8wrl
+4  A: 

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?"

Daniel Earwicker
Comment from downvoter?
Daniel Earwicker