Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Binding in C#

class A 
 {
   public virtual void WhoAreYou() { Console.WriteLine("I am an A"); }
 }
class B : A
{
  public override void WhoAreYou() { Console.WriteLine("I am a B"); }
}
class C : B
{
 public new virtual void WhoAreYou() { Console.WriteLine("I am a C"); }
}
class D : C 
{
  public override void WhoAreYou() { Console.WriteLine("I am a D"); }
}


C c = new D();
c.WhoAreYou();// "I am a D"
A a = new D();
a.WhoAreYou();// "I am a B" !!!!

How the reference is allocated internally,reference A contains the reference of B? Can any one explain Whats going On?

like image 550
C-va Avatar asked Jun 01 '12 15:06

C-va


People also ask

Is there dynamic binding in C?

C is a statically compiled language, it doesn't really have "dynamic binding". You can do it manually using API:s such as POSIX' dlopen() , but I would hesitate to call that "binding" although in a sense I guess it is.

What is dynamic binding explain with example?

We also call Dynamic binding as Late Binding because binding takes place during the actual execution of the program. The best example of Dynamic binding is the Method Overriding where both the Parent class and the derived classes have the same method.

What is static and dynamic binding in C?

Static binding happens when all information needed to call a function is available at the compile-time. Dynamic binding happens when the compiler cannot determine all information needed for a function call at compile-time.

What is binding in C programming?

Master C and Embedded C Programming- Learn as you go The binding means the process of converting identifiers into addresses. For each variables and functions this binding is done. For functions it is matching the call with the right function definition by the compiler.


1 Answers

In class C, the method WhoAreYou() doesn't override the base class method, as it is defined with new keyword which adds a new method with the same name which hides the base class method. That is why this:

C c = new D();
c.WhoAreYou();// "I am a D"

invokes the overridden method in D which overrides its base class method defined with new keyword.

However, when the target type is A, then this:

A a = new D();
a.WhoAreYou();// "I am a B" !!!!

invokes the overridden method in B, as you're calling the method on a of type A whose method is overriden by B.

like image 57
Nawaz Avatar answered Oct 06 '22 20:10

Nawaz