A question about virtual methods

S

Sam Kong

Hello!

I'm learning C# and while trying things I encountered an issue that I
don't understand.

Here's the code:

------------

using System;

class MyClass
{
public override string ToString()
{
return "Test";
}


}

class MainClass
{
public static void Main(string[] args)
{
MyClass o = new MyClass();
Console.WriteLine(o.ToString()); //prints "Test"
Console.WriteLine(((object)o).ToString()); //prints "Test" also
//however, I expected "System.Object".
}
}

--------------

Console.WriteLine(((object)o).ToString());

Why does this line print "Test" instead of "System.Object"?
I cast the type and it doesn't seem to work.
Am I understanding it incorrectly?

Thanks.

Sam
 
J

Jon Skeet [C# MVP]

Why does this line print "Test" instead of "System.Object"?
I cast the type and it doesn't seem to work.
Am I understanding it incorrectly?

Yes, you are. The main point of polymorphism is that you don't need to
know the exact type of the object in order to get its overridden
behaviour. If it *didn't* behave this way, how would something like
Hashtable work?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top