1

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?

jpo
  • 3,959
  • 20
  • 59
  • 102
  • 1
    `public string var;` so much pain in one line... I think the only way to make that more eye-catching (in a bad way) would be `public String var;` ;p – Marc Gravell Oct 24 '13 at 12:54
  • sorry, just wanted to shortcut the word variable – jpo Oct 24 '13 at 13:03

2 Answers2

1

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.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

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;
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900