How can we Achieve Late binding in C#.Can any give one example.
Answer Posted / saurabh
Its using Virtual functions.
When compiler encounters virtual keyword in an function
defination, instead of binding to the function directly,
the compiler writes a bit of dispatch code that at runtime
will look at calling objects realtype and calls the
function accordingly.
EX.
class baseClass
{
protected virtual void PrintMessage()
{
Console.WriteLine("Hi From Base Class");
}
}
class derivedClass : baseClass
{
protected override void PrintMessage()
{
Console.WriteLine("Hi From Derived Class");
}
}
public static void Main()
{
baseClass b = new baseClass();
baseClass bd = new derivedClass();
b.PrintMessage(); // prints "Hi From Base Class"
bd.PrintMessage(); // prints "Hi From Derived Class"
}
Here the runtime detects the correct type of object stored
in bd i.e. derivedClass and calls dericedClass
implementation of PrintMessage().
| Is This Answer Correct ? | 20 Yes | 4 No |
Post New Answer View All Answers
What are fields in c#?
Can we inherit sealed class in c#?
What is a static field?
What is exe file in c#?
How big is a 64 bit integer?
explain the features of static/shared classes.
What operators can be used to cast from one reference type to another without the risk of throwing an exception?
How to open a new form on button click in Windows forms?
What is the difference between malloc () and new?
Can we extend sealed class in c#?
Define an assembly in .net?
How we can create an array with non-default values?
Write a program to find the angle between the hours and minutes in a clock
What is the .NET collection class that allows an element to be accessed using a unique key?
What is form feed in c#?