Reputation: 1242
This is the code. If I want to call DerivedFunction1() in CallFunction(), how can I do that?
namespace Inheritance_Console
{
class Base
{
}
class DerivedClass1 : Base
{
public void DerivedFunction1() // this fucntion is to be called...
{
}
}
class DerivedClass2 : Base
{
public void DerivedFunction2()
{
}
}
class Program
{
static void Main(string[] args)
{
Base objBase = new DerivedClass1();
CallFunction(objBase);
}
static void CallFunction(Base objBase)
{
//......here
objBase. //DerivedFunction1 is not accessible here.
}
}
}
This is not an actual implementation, its an interview question. I don't know what more details to add. Please ask if you think something else is needed here.
Upvotes: 0
Views: 49
Reputation: 35318
You need to cast it into a DerivedClass1
:
if (objBase is DerivedClass1) ((DerivedClass1) objBase).DerivedFunction1();
Note how I'm checking if it's actually a DerivedClass1
first to avoid the invalid cast exception.
Upvotes: 2