Let say we have Class A and Class B. ClassB extends Class A. (ClassB : ClassA)
Now let's say that whenever I instantiate ClassB, I'd like to Run some Random code and only then call "base" to reach ClassA constructor.
Like:
class ClassA
{
public ClassA()
{
Console.WriteLine("Initialization");
}
}
class ClassB : ClassA
{
public ClassB() //: base()
{
// Using :base() as commented above, I would execute ClassA ctor before // Console.WriteLine as it is below this line...
Console.WriteLine("Before new");
//base() //Calls ClassA constructor using inheritance
//Run some more Codes here...
}
}
In the programming language I usually work with, I can do that, by simply calling super()
after Console.WriteLine()
; But I cant make it in C#. Is there any other syntax or other way to do that?
Another hack if you can get away with calling a static method.
There's a hacky way of doing it using an instance variable initializer:
The less hacky way of doing it is to rethink how you construct a
ClassB
to start with. Instead of having clients call the constructor directly, provide a static method for them to call:Recently I ran into a scenario where I needed to calculate some logic before passing the result into base.
I could just do something like
But I find that to be ugly, and can get really long horizontally. So I opted instead to use Func Anonymous methods.
E.g. imagine you have a base class,
Now you inherit from that and want to do some logic to determine the sql query text,
In this way you can execute code before Base is called and (in my opinion) it's not really hacky.