Search code examples
c#nullablec#-6.0optional-values

Converting from one nullable type to another nullable type


How can one convert from a nullable instance of class A to nullable instance of class B, while B is subclass of A, I tried this but it crashes:

class A
{
}

class B:A
{
}

A? instance_1=something_maybe_null;

if (instance_1.GetType() == typeof(B))
{
    ((B)(instance_1))?.some_method_in_B(paramters);
}

And if I move ? into parathesis, it doesn't compile:

...
if (instance_1.GetType() == typeof(B))
{
    ((B)(instance_1)?).some_method_in_B(paramters);
}

Solution

  • I am assuming this is a typo A? instance_1=something_maybe_null; because you cannot do nullable reference types (i.e. classes), at least in C# 6.

    If I understand your intent correctly, you just want to conditionally call a method in B if the object is actually an instance of B. If so, then you can do this:

    class A
    {
    }
    
    class B : A
    {
        public void SomeMethodInB() {  }
    }
    
    A instance_a = something_maybe_null;
    B instance_b = instance_a as B;
    instance_b?.SomeMethodInB();