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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With