Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access the base class method with derived class objects

Tags:

c#

If I am using shadowing and if I want to access base class method with derived class objects, how can I access it?

like image 778
3692 Avatar asked Apr 11 '12 10:04

3692


People also ask

Can derived class objects be assigned to base class?

In C++, a derived class object can be assigned to a base class object, but the other way is not possible.

Can base class access derived class private?

Derived class can not access the private members of it's base class. No type of inheritance allows access to private members.


2 Answers

Use the base keyword:

base.MethodOnBaseClass();

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

like image 198
Oded Avatar answered Oct 14 '22 13:10

Oded


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
    }
}
like image 30
3692 Avatar answered Oct 14 '22 13:10

3692