A question about virtual methods

  • Thread starter Thread starter Sam Kong
  • Start date Start date
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
 
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?
 
Back
Top