C# Getting inherited variables (initialized in "OnActionExecuting") value in child constructor

307 views Asked by At

I have a parent class classA with a variable defined as public string variable. This variable var is initialized in the OnActionExecuting method defined as protected override void OnActionExecuting(ActionExecutingContext test) A child class inherits from this class as public class classB : classA However, ths code below fails

public class classB : classA{
   string h;
   public classB(){
      h = this.variable
   }
 }

That is, the variable var is null. However, if I declare a public variable variable2 in classA and initialize it on the fly public string variable2 = "test", I can retrieve it in the controller. How can I edit this code so that initialization happening in OnActionExecuting can be accessed in the constructor of the inheriting classes?

2

There are 2 answers

0
Marc Gravell On BEST ANSWER

OnActionExecuting is invoked after the constructor, so: there is no way to get the value of something that hasn't happened yet.

If the inheriting class needs a value that is only available when the base-type's OnActionExecuting method has fired, then: access it then:

protected override void OnActionExecuting(ActionExecutingContext ctx)
{
    base.OnActionExecuting(ctx);
    h = this.var;
}
0
Daniel Hilgarth On

OnActionExecuting most likely is not called in the constructor of classA, which means that is called by whoever creates the new instance of classB. As such, it will be called only after the constructor is run to completion.

So, what you request is not possible.

Think about it:
You can't eat your pizza before ordering it.