How to check from within the base class if it is an instance of a derived class:
class A0 : A {};
class A1 : A {};
class A2 : A {};
class A
{
void CheckDerived()
{
if (this is A0)
{
//Do something when instance is A0
}
else if (this is A1)
{
//Do something when instance is A1
}
else if (this is A2)
{
//Do something when instance is A2
}
}
}
The code in the question should do what you want, however, as Danny Goodball wrote in his comment, this is a very bad practice.
According to the open/close principle, stating that "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification",
The proper way to handle different actions for different children is using override:
Make the method virtual (might be even better as an abstract method), and override it in each derived class with it's own implementation:
class A
{
virtual void CheckDerived() { throw new NotImplementedException(); }
}
class A0 : A
{
override void CheckDerived() { Console.WriteLine("A0"); }
}
class A1 : A
{
override void CheckDerived() { Console.WriteLine("A1"); }
}