Evgeny
Evgeny

Reputation: 3322

C# Refactoring: check type of the derived class and assign to a variable of the same class

I have a number of classes that derived from an abstract class. In a method, I receive an object, which is one of the derived classes. I need to check the type of an object and assign to a correct property. The straightforward solution works, but looks like it can be refactored. I do not know how to approach it, though:

    public MyDerived1 derived1;
    public MyDerived2 derived2;
    // ....
    public MyDerivedX derivedX;

    public void AssignValue(MyBaseClass entity)
    {
        var derivedOne = entity as MyDerived1;
        if (derivedOne != null)
        {
            derived1 = derivedOne;
            return;
        }

        var derivedTwo = entity as MyDerived2;
        if (derivedTwo != null)
        {
            derived2 = derivedTwo;
            return;
        }

        // ....

        var derivedEx = entity as MyDerivedX;
        if (derivedEx != null)
        {
            derivedX = derivedEx;
            return;
        }
    }

Upvotes: 1

Views: 161

Answers (2)

Z.R.T.
Z.R.T.

Reputation: 1603

maybe you looking for something like that:

    public void AssignValue(MyBaseClass entity)
    {
        var item = this.GetType().GetFields().FirstOrDefault(x => x.FieldType == entity.GetType());
        if (item != null)
        {
            item.SetValue(this, entity);
        }
    }

Upvotes: 0

Aleks Andreev
Aleks Andreev

Reputation: 7054

You can create generic version of AssignValue like this:

private static bool AssignValue<T>(MyBaseClas entity, out T derived) where T : MyBaseClas
{
    var t = entity as T;
    if (t == null)
    {
        derived = null;
        return false;
    }

    derived = t;
    return true;
}

now you can use it in this way:

MyDerived1 derived1;
MyDerived2 derived2;

var _ = AssignValue(entity, out derived1)
    || AssignValue(entity, out derived2);

Generic function returns bool to skip pending type checks on first match

Upvotes: 2

Related Questions