3692
3692

Reputation: 628

Access the base class method with derived class objects

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

Answers (4)

Ganesh Pandey
Ganesh Pandey

Reputation: 41

DerivedClass derivedObj = new DerivedClass(); 
(derivedObj as BaseClass).Method1(); // cast to base class with method invoke

Upvotes: 4

Luchian Grigore
Luchian Grigore

Reputation: 258548

You qualify the method call:

base.foo();

Upvotes: 9

3692
3692

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

Oded
Oded

Reputation: 498904

Use the base keyword:

base.MethodOnBaseClass();

The base keyword is used to access members of the base class from within a derived class:

Upvotes: 23

Related Questions