Reputation: 628
If I am using shadowing and if I want to access base class method with derived class objects, how can I access it?
Upvotes: 8
Views: 29075
Reputation: 41
DerivedClass derivedObj = new DerivedClass();
(derivedObj as BaseClass).Method1(); // cast to base class with method invoke
Upvotes: 4
Reputation: 628
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
}
}
Upvotes: 15