The problem with constructors and inheritance in C #

I have the following problem:

public class A { public A(X, Y, Z) { ... } } public class B : A { public B(X, Y) : base(X, Y) { //i want to instantiate Z here and only then pass it to the base class! } } 

How can I solve this problem? Is there any way?

+7
inheritance constructor c #
source share
4 answers

A common solution is to call a static method of the type that can calculate the value of the parameter passed to the base constructor.

For example:

 public B(int x, int y) : base(x, y, CalculateZ(x, y)) { } // You can make this parameterless if it does not depend on X and Y private static int CalculateZ(int x, int y) { //Calculate it here. int exampleZ = x + y; return exampleZ; } 

Note that CalculateZ cannot be an instance method, because the this link is not available in constructor initializers.

From the language specification 10.11.1 Constructor Initializers:

The instance constructor initializer cannot access the instance being created. Therefore, this is a compile-time error for referencing this in the constructor initializer argument expression, as well as a compile-time error for the expression argument for referencing any member instance through a simple name.

EDIT: Changed "instance" to "static" in the description.

+13
source share

You need to calculate Z before the constructor itself is called. If it is simple, you can use the built-in expression, otherwise you will need to define a helper function.

Using helper function:

 public class A { public A(X x, Y y, Z z) { ... } } public class B : A { private static Z calculateZ() { } public B(X x, Y y) : base(X, Y, calculateZ()) { } } 

Without helper function:

 public B(X, Y) : base(X, Y, X+Y) { } 
+2
source share
 public abstract class A { public A(X, Y) { ... } public abstract Z TheVariableZ{get;set;} } public class B : A { public B(X, Y) : base(X, Y) { //i can only calculate Z here! } public override Z TheVariableZ{//implement it here} } 

And if you cannot make A abstract, just mark the property as virtual

+1
source share

Perhaps it:

 public abstract class A { public A(X, Y) { CalculateZ(); } abstract void CalculateZ(); } public class B : A { public B(X, Y) : base(X, Y) { } override void CalculateZ() { ... Calculate here. } } 
+1
source share

All Articles