Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with constructors and inheritance in C#

I am having 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 a way?

like image 842
devoured elysium Avatar asked Nov 18 '10 10:11

devoured elysium


2 Answers

The common solution is to call a static method belonging to the type that can calculate the value of the parameter to be 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;
}

Do note that CalculateZ cannot be an instance method, because the this reference is not available in constructor initializers.

From the language-specification 10.11.1 Constructor initializers:

An instance constructor initializer cannot access the instance being created. Therefore it is a compile-time error to reference this in an argument expression of the constructor initializer, as is it a compile-time error for an argument expression to reference any instance member through a simple-name.

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

like image 134
Ani Avatar answered Sep 26 '22 12:09

Ani


You need to calculate Z before the constructor itself gets called. If it's simple you can use an inline expression, else you'll need to define a helper function.

Using a helperfunction:

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 helperfunction:

public B(X, Y) : base(X, Y, X+Y) {

}
like image 45
CodesInChaos Avatar answered Sep 25 '22 12:09

CodesInChaos