Your test program 'printf method gets a single parameter of Type Base: so, even if a valid instance of Class A, or Class B, is passed to it, it will always call the 'printf method defined in Base.
By declaring the parameter of Type Base, you essentially down-cast the instance of A, or B, to Type Base.
One way you could avoid this, with minimum code, would be to make the parameter Type 'dynamic and let that "do the work" for you of calling the right method for each Class Type:
public Base baseClass = new Base();
public DerivedA derivedA = new DerivedA();
public DerivedB derivedB = new DerivedB();
public class testProgram
{
public void print(dynamic baseClass)
{
baseClass.printf();
}
}
However, you pay a price for using 'dynamic, and, until you are more advanced in C# programming, you may want to wait until you fully understand how 'dynamic (late binding) works before using it in your code.
Another way you can make your code use the "right Type" is to evaluate the Type:
public class testProgram
{
public void print(Base baseClass)
{
if (baseClass is DerivedA)
{
(baseClass as DerivedA).printf();
}
else if (baseClass is DerivedB)
{
throw new InvalidProgramException("DerivedB don't print");
}
else
{
baseClass.printf();
}
}
}
But, why have a 'printf Method in Class DerivedB if you don't want to use it ?
I suggest you consider using the 'new method modifier when you are creating methods in derived classes when you wish to "hide" the method defined in the base Class:
public class DerivedA : Base
{
public new void printf()
{
Console.WriteLine("I am from derived A !!!");
}
}
public class DerivedB : Base
{
public new void printf()
{
Console.WriteLine("I am from derived B !!!");
}
}
Using 'new (even though not necessary here: you'll get a compiler warning, but, not an error) makes the
intent of your code clear. See: [
^].