Reputation: 192
I've read the following statement about dynamic binding:
Which method to invoke is determined by variable's actual type and not declared type. This is known as dynamic binding.
But then why is the following code not working the way I expect it to?
class Program
{
static void Main(string[] args)
{
Parent parent = new Parent();
parent.SomeMethod(); // overriden
parent.AnotherMethod(); // hidden
Child child = new Child();
child.SomeMethod();
child.AnotherMethod();
System.Console.WriteLine("---------------------------------------");
Parent parent1 = new Child();
parent1.SomeMethod();
parent1.AnotherMethod();
}
}
class Parent
{
public virtual void SomeMethod() //override
{
System.Console.WriteLine("Parent.SomeMethod");
}
public void AnotherMethod() //hide
{
System.Console.WriteLine("Parent.AnotherMethod");
}
}
class Child : Parent
{
public override void SomeMethod() //overriden
{
System.Console.WriteLine("Child.SomeMethod");
}
public new void AnotherMethod() //hidden
{
System.Console.WriteLine("Child.AnotherMethod");
}
}
The output of the above code is:
Parent.SomeMethod
Parent.AnotherMethod
Child.SomeMethod
Child.AnotherMethod
Child.SomeMethod
Parent.AnotherMethod <-- Shouldn't this be Child.SomeMethod? I'm confused please explain
Upvotes: 2
Views: 170
Reputation: 15906
From New Vs Override
You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
From new modifier (C# Reference)
Upvotes: 2
Reputation: 107387
You are upcasting variable parent1
back to class type Parent
in this assignment:
Parent parent1 = new Child();
Because AnotherMethod
isn't polymorphic (since you haven't applied virtual
/ override
), and in fact you've explicitly added the new
keyword to tell the compiler that the AnotherMethod
symbol is reused between Child
and Parent
(i.e. There's no dynamic binding on AnotherMethod
).
As a result, compiler will resolve the Parent's AnotherMethod
symbol at compile time because of the variable type (Parent parent1
), irrespective of the fact that the actual run time type allocated on the heap is a Child
instance.
You can access the Child AnotherMethod
by using another downcast:
((Child)parent1).AnotherMethod();
Upvotes: 2