Search code examples
c#classderivative

Get derivative method on base class variable


I have two classes a base class b and the derivative. In my code I call a method with a base class parameter, but I want to detect if the parameter is the derivative. In the case it is the derivative, I want to call a method that is only in the derivative.

Example of my code:
Classes

public class Base {}

public class Derivative : Base {
    public void foo() {
        //do something...
    }
}

Method with parameter:

void Action (Base b) {
    if (b is Derivative) {
        b.foo();
    }
}

The problem is that it treats b as a Base class. Is it possible to keep this reference but use the derivative classes methods?


Solution

  • In modern C#:

    void Action (Base b) {
        if (b is Derivative derived) {
            derived.foo();
        }
    }
    

    In older C#:

    void Action (Base b) {
        var derivative = b as Derivative;
        if(derivative != null) derivative.foo();    
    }
    

    I'd be wary of this pattern, but that's outside the scope of this question