How to tracktrace code that uses polymorphism in C SolutionE
How to track/trace code that uses polymorphism in C# ?
Solution
Example :-
class Base
{
public virtual void Display()
{
System.Console.WriteLine(\"Base::Display\");
}
}
class Derived : Base
{
public override void Display()
{
System.Console.WriteLine(\"Derived::Display\");
}
}
class Demo
{
public static void Main()
{
Base b;
b = new Base();
b.Display();
b = new Derived();
b.Display();
}
}
Output :-
Base :: Display
Derived :: Display
Explanation :-
The above example implements runtime polymorphism i.e methid overriding.
Firstly we define a base class with display method as virtual so as to enable overriding on it.
Then a class is derived from base class with the same method named display using override keyword to imply that it implies the method in base class.
Then in main method ,of class Demo ,we create a base class reference b and then assign newly created base class object.now the display method is called using reference b which calls the base class method.
But later reference b is re assigned to new derived class object.and now if we try calling the display method the derived class version is called.
The only way to trace this process is using debugging technique where we set brekpoints at assignmentand method calls in the main method to check which objects are being accessed as per their object hash code and their corresponding methods.

