Create a base class with a method that uses a switch case that reference the type of the children class.
Is the below piece of code violating the OO principles, if so which one?
public abstract class BaseClass
{
public BaseClass Method()
{
switch (this)
{
case DerivedClass1 s:
return new DerivedClass1();
case DerivedClass2 c:
return new DerivedClass2();
case DerivedClass3 r:
return new DerivedClass3();
default:
return null;
}
}
}
You're violating the open-closed principle of SOLID by not taking advantage of polymorphism. Make the base class method virtual
and override
it for each derived class:
public abstract class BaseClass
{
public virtual BaseClass Method()
{
return null;
}
}
public class DerivedClass1 : BaseClass
{
public override BaseClass Method()
{
return new DerivedClass1();
}
}
...and so on.