Advanced base constructor calls in C#

by Marcel Veldhuizen 5. September 2013 14:00

Note: This article was edited after a Gonçalo Lopes presented me with a better solution. Thanks!

Every now and then you run into a situation where you wish your programming language of choice was just a tad more flexible than it actually is. For example, constructors in C# always have to directly call one of the base type constructors as the first thing they do (or do they? keep reading).

Yesterday I ran into a situation where I would like my derived class to always use the same implementation* for a certain injectable dependency. No problem:

public class FooBase
    public FooBase(IDependency dependency)    { /* stuff here */ }

public class MyFoo : FooBase
    public MyFoo() : base(new MyDependency()) { }

The dependency is created on the fly and my base class constructor is happy. However, my derived class also needed to make use of this dependency and my base class does not expose any property or field for me to access it. So before calling the base constructor, I would have liked to store a reference to this newly created MyDependency object.


Tags: ,

Programming | .NET

Marcel Veldhuizen

Software Architect by profession, mostly focused on Microsoft .NET technology.

Metal enthusiast; I love going to concerts :)



Recent Tweets

Note: For Customization and Configuration, CheckOut Recent Tweets Documentation