ilitirit
ilitirit

Reputation: 16352

Is there a way to get a reference to the base class in C#?

I'm working on some legacy code that uses classes, methods and all sorts of patterns that weren't designed for testability. I'd like to create unit tests for changes that were added, but I don't want the base class functionality to be called if I provide a surrogate (the base class methods access a database resource).

What I want to do is effectively similar to:

public override void DoSomething()
{
        // Perform some custom logic before calling the base implementation
        // ...
        // ...

        // The keyword base is not valid in this context
        (BaseClassSurrogate ?? base).DoSomething();

        // Some more custom logic
        // ...
        // ...
}

Is something like this possible in C#, or is there an alternate way of testing this that doesn't involve a complex refactor?

Upvotes: 1

Views: 140

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503300

You can't achieve it like that, because base.Xyz() and BaseClassSurrogate.Xyz() would end up using different IL.

You can achieve it as:

if (BaseClassSurrogate is null)
{
    base.DoSomething();
}
else
{
    BaseClassSurrogate.DoSomething();
}

That's really ugly, but I'd expect it to work.

Upvotes: 3

Related Questions