0

Imagine this code:

using System;

public enum BaseClassType
{
    DerivedA,
    DerivedB
}

public abstract class BaseClass
{
    public BaseClassType Type;

    public BaseClass(BaseClassType type)
    {
        Type = type;
    }

    public virtual void Interact()
    {
        Console.WriteLine("BaseClass.Interact()");
    }
}

public class DerivedA : BaseClass
{
    public DerivedA() : base(BaseClassType.DerivedA) {}

    public void SomeMethodA(int signature0, float signature1)
    {
        Console.WriteLine("DerivedA.SomeMethodA");
    }
}

public class DerivedB : BaseClass
{
    public DerivedB() : base(BaseClassType.DerivedB) {}

    public void SomeMethodB(float signature0)
    {
        Console.WriteLine("DerivedB.SomeMethodB");
    }
}

public class Test
{
    public static void Main()
    {
        BaseClass[] elements = new BaseClass[] { new DerivedA(), new DerivedB() };
        foreach (var element in elements)
        {
            switch (element.Type)
            {
                case BaseClassType.DerivedA:
                    (element as DerivedA).SomeMethodA(5, 5f);
                    break;
                case BaseClassType.DerivedB:
                    (element as DerivedB).SomeMethodB(3f);
                    break;
            }
        }
    }
}

I wonder what is the best OOP way to get rid off this type of switch? Maybe some pattern? The methods of the subclasses have completely different signatures, so I cannot extract it and make virtual in the base class.

  • You're confusing polymorphism (overriding base class methods) with Inheritance (adding methods). You cannot call the derived methods from a base class type. You can attempt to case the object, and if it succeeds call the method, or you can switch as shown, but really - if you're iterating over a base class collection, you should be dealing with the objects as base classes. – gbjbaanb Sep 15 '15 at 11:53
1

If your subclasses have methods with different types and values as parameters, then those aren't the same methods. They should be encapsulated behind a common, inherited method that knows what is appropriate to the concrete class.

If it isn't possible to for the subclass to get at these values, then your class hierarchy is flawed: the subclass is supposed to express a specialization of a some type that differs in some specifics, but it doesn't know these specifics! This is not something a design pattern can fix - you have to redraw the class boundaries in your system to make the types fit your business domain

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.