While working on a C# program this week, came across interesting scenario where I needed to pass parameter to base constructor of a class. Unfortunately, base constructor is developed by a third party, so we don't really couldn't change it.
Early days when we use this base class, we use to hard code the parameter to it in inherited class constructor. This week we had a new requirement, where that parameter required to be dynamic or read from configuration file.
To demonstrate it with example, let's assume my base class is ISOCar (where it build ISO standard car). I inherit this class and create my own modified car - let's call it MyBrandCar. Let's also assume base class has one constructor which accept engine capacity. So my code will be some like below:
public class MyBrandCar : ISOCar
{
public MyBrandCar() : base(1.5)
{
}
}
My new requirement is, I need to read the engine capacity from a config file or calculate it from some other values from a config file.
So I was wondering what is the best way to approach this. Because constructor is called first and base constructor is called even before inherited class constructor, there was no way to fetch the value from the config file.
Little bit of Google suggested me to use static method. So I changed my code to following:
public class MyBrandCar : ISOCar
{
public static decimal GetEngineCapacity()
{
// read the config and return the value
}
public MyBrandCar() : base(GetEngineCapacity())
{
}
}
Since static methods are executed even before constructors, this has worked.
Simple, but elegant way,