Search code examples
c#inheritancecastingderived-class

Shorter version of assigning to a member of a derived class by an instance of a base-class


Consider this small example:

public class BaseClass { }
public class DerivedClass : BaseClass { public int Field; }

public static class Program
{
    public static void Main( string[] args)
    {
        BaseClass baseVar = new DerivedClass();

        if( baseVar is DerivedClass )
        {
            var derivedVar = (DerivedClass)baseVar;

            derivedVar.Field = 1;

            baseVar = derivedVar;
        }
    }
}

I have alot of code like this in if-conditions. Is there a shorthand version of this, so I do not have to create a temporary derived variable?


Solution

  • One way would be safe typecasting:

    BaseClass base = new DerivedClass();
    DerivedClass derived = base as DerivedClass;
    derived?.Field = 1;
    

    Note: as is safe casting - which will either cast or return null. ? is a C#6 Feature, where the method or the assignment is executing when the variable is not a nullPtr. You do not have to write baseVar = derivedVar, since both are bound by reference. When you cast and change the field, then the reference hasn't changed at all.

    Also, here's a MSDN article on null propagation in C#6.0 https://msdn.microsoft.com/de-de/magazine/dn802602.aspx

    For the sake of compliance, that's the veriant OP chose:

    BaseClass base = new DerivedClass();
    (base as DerivedClass)?.Field = 1;