Access the base class method with derived class objects
c#
Solution
First cast the derived class object to base class type and if you call method it invokes base class method. Keep in mind it works only when derived class method is shadowed.
For Example,
Observe the commented lines below:
public class BaseClass
{
public void Method1()
{
string a = "Base method";
}
}
public class DerivedClass : BaseClass
{
public new void Method1()
{
string a = "Derived Method";
}
}
public class TestApp
{
public static void main()
{
DerivedClass derivedObj = new DerivedClass();
BaseClass obj2 = (BaseClass)derivedObj; // cast to base class
obj2.Method1(); // invokes Baseclass method
}
}
Problem
If I am using shadowing and if I want to access base class method with derived class objects, how can I access it?