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
Can I use ReaderWriterLock instead of Monitor.Enter/Exit for Threading?
Explain the 3 types of properties in c# with an example?
What's the difference between class and object?
Explain the role of the datareader class in ado.net connections?
What is delimiter in c#?
What is lambda expression in c#?
Is string a primitive data type in c#?
Can abstract class have private constructor c#?
What is delegates and events?
What is difference between write and writeline?
What is oledb in c#?
What is datagrid c#?
How many constructor can a class have?
How can I process command-line arguments?
what are the Disadvantages of vb