Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic method dispatch

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi,I completly understand virtual methods and polymorphism(one interface,multiple methods),but I don't understand why is it so important that a call to overridden function is resolved at runtime(runtime means when exe or dll file starts running,right?) and not compiled time?
Why is that so good?

If you have

Console.Read(i);

if(;i<10)
{
first()<
}

else
{
second()<
}

Isn't a call to one of those two methods also resolved at runtime?

Thanks for helping me out
 
Polymorphism
This threw me for a long time too. When Microsoft uses the word &quot;Polymorphism&quot; in regards to .NET, they mean being able to call a method in a class that has inherited from another class, and be sure of getting the correct method. Whenever you hear &quot;Polymorphism&quot;, think &quot;virtual&quot;.

So if you have a method in class A:
Code:
public class A {
public int virtual Foo() {
  Console.Writeline(&quot;In Class A Foo&quot;);
};
}
You can override that method in other classes that inherit from A:
Code:
public class B : A{
public int override Foo() {
  Console.Writeline(&quot;In Class B Foo&quot;);
};
}
//-------
public class C : A{
public int override Foo() {
  Console.Writeline(&quot;In Class C Foo&quot;);
};
}

Chip H.
 
Thank you.Can you tell me why is it so important that a call to overridden function is resolved at runtime and not compiled time?What do we gain with that?
 
Because you can set up a method that takes a variable of type Class A, and pass in variables of type Class B or Class C with no problems. Inside the method you can call one of the methods inherited from Class A, and the system will actually call the methods in Class B or Class C as appropiate.

Chip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top