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?
You can't do that with C#. Your best bet is to extract that code into it's own method in the parent and then call that from the child when you're ready.
C# doesn't allow calling base constructors inside constructor bodies, different from Java.
Another elegant solution would be to completely rethink how your objects are constructed. In the constructor of your base class you can call your own
construct
function, and you omit dependent future constructors, in the following way:I had the same problem. I found this solution to be the best if you don't have access to the base class.
You can not call base constructor. But a different thing is that when you declare an object of derived class both constructor derived and base is called.
Actually, you can:
Output:
But I will prefer to not use this trick if it is possible.