Is there any way in which you can call super constructor at the end of descendant class constructor?
It works in Java, but in C# the keyword base
doesn't seem to be equivalent to Java's super.
Example:
class CommonChest : BasicKeyChest
{
public CommonChest()
{
Random rnd = new Random();
int key = rnd.Next(1, 6);
int coins = rnd.Next(70, 121);
super(key, coins, "Common");
}
}
To call the parameterized constructor of base class inside the parameterized constructor of sub class, we have to mention it explicitly. The parameterized constructor of base class cannot be called in default constructor of sub class, it should be called in the parameterized constructor of sub class.
The compiler knows that when an object of a child class is created, the base class constructor is called first.
Most of the time the runtime will call the base class default constructor for you when you create your derived class object, so you do not need to call "base()". By default, a derived class when instantiated will always IMPLICITLY call the base class default constructor.
In C# terms, the base constructor is executed first.
There is no way to postpone the call to the base constructor, it must complete before the derived constructor starts.
However, you can perform computations outside the derived constructor prior to calling the base constructor by providing an expression that you pass to the base:
class CommonChest : BasicKeyChest {
public CommonChest()
: this(GenTuple()) {
}
private CommonChest(Tuple<int,int> keysCoins)
: base(keysCoins.Item1, keysCoins.Item2, "Common") {
}
private static Tuple<int,int> GenTuple() {
Random rnd = new Random();
int keys = rnd.Next(1, 6);
int coins = rnd.Next(70, 121);
return Tuple.Create(keys, coins);
}
}
The above is a little tricky: a private constructor that takes a pair of ints is used to forward these ints to the base constructor. The tuple is generated inside GenTuple
method, which is invoked before calling the base
constructor.
NO, the concept of using base
keyword or Constructor Initializer
is that the base constructor gets called first and then child constructor. So that all common or shared parameters across the childs gets initialized first and then specific properties of child classes. That's also one of the reason why an abstract
class can have Constructor
You could call a static method within the call to the base constructor:
class CommonChest : BasicKeyChest
{
public CommonChest() : base(DoSomething())
{
}
private static Tuple<int,int> DoSomething()
{
Random rnd = new Random();
int key = rnd.Next(1, 6);
int coins = rnd.Next(70, 121);
return Tuple.Create(key, coins);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With