Could you explain to me. How i have to resolve simple task below?
class Base{}
class Derived1: Base { void Method(); }
class Derived2: Base { void Method();}
static void Main(string[] args)
{
Base object; //it is just a declaring
if (some condition is true)
object = new Derived1();
else
object = new Derived2();
//now i want to call one of methods of one of my derived classes
//object.MyMethod(); //of course wrong, object has no that method
//ok, i have to downcast it but i don't know which class to
//((object.GetType())object).Method(); //wrong
//is there only one way is to repeat conditions
//and to downcast explicitly?
if (some condition is true again)
(object as Derived1).Method();
else
(object as Derived2).Method();
}
Base class is know nothing about Method() of course.
I suggest using abstract method in the Base
class overriden in both derived ones:
abstract class Base { public abstract void Method();}
class Derived1: Base { public override void Method(); }
class Derived2: Base { public override void Method(); }
Then
static void Main(string[] args) {
Base instance;
if (some condition is true)
instance = new Derived1();
else
instance = new Derived2();
instance.Method();
}
Implementing interface is an alternative:
interface IBase {void Method();}
class Derived1: IBase { void Method(); }
class Derived2: IBase { void Method(); }
static void Main(string[] args) {
IBase instance;
if (some condition is true)
instance = new Derived1();
else
instance = new Derived2();
instance.Method();
}