Can anyone explain the behaviour of this code , as I'm playing with polymorphism I came up with this code by coincidence, and I'm really confused with its behaviour:
public class Book
{
public virtual void Method()
{
Console.WriteLine("Book/ I am here in "+ GetType().Name);
}
}
class Chapter : Book
{
public new void Method()
{
Console.WriteLine("Chapter/ I am here in "+ GetType().Name);
}
static void Main()
{
Book myBook = new Chapter() ;
myBook.Method();
}
}
The output from this program is
Book/ I am here in Chapter
This means that the instance called the method within the book class but gets the type chapter
. Does GetType()
method depend on the instance it called with, not the class it lies in?
Yes, GetType()
gets the actual type from the object (instance) at runtime.
If you changed public new void Method()
to public override void Method()
it would print out the other line.
See MSDN:
Return Value
Type: System.Type
The exact runtime type of the current instance.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments