Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access base class A function by drived class B object in c#

Tags:

c#

oop

Access base class A function by derived class B object in c# Is there is any way i can access function(Sum) of A class By B class object and get output 10.?

Class A
{
    public int Sum(int i)
    {
        return i+3;
    }
}

Class B:A
{
     public int Sum(int i)
     {
          return i+4;
     }
}

B objectB=new B();

int result=objectB.Sum(7);

output:11
like image 844
Jatinder Sharma Avatar asked Oct 23 '13 00:10

Jatinder Sharma


1 Answers

Declare an A variable instead of B, while still using B's constructor.

A objectB = new B();
int result=objectB.Sum(7);

This will use A's method. This is only true because the method is shadowed and not overridden.

You will also get a compiler warning for your method Sum in B and you might want to define it as public new int Sum(int i) to signal that the hiding is intended.

like image 163
dee-see Avatar answered Oct 28 '22 08:10

dee-see