zs2020
zs2020

Reputation: 54514

Declare and create variable in code behind

Here are 3 scenarios:

namespace NS
{
    public partial class A: System.Web.UI.UserControl
    private Variable v;
    protected void Page_Load(object sender, EventArgs e){
        if (!Page.IsPostBack) v= new Variable();
        ....
    }
}

namespace NS
{
    public partial class A: System.Web.UI.UserControl
    private Variable v = new Variable();
    protected void Page_Load(object sender, EventArgs e){
    }
}

namespace NS
{
    public partial class A: System.Web.UI.UserControl
    private Variable v;
    protected void Page_Load(object sender, EventArgs e){
        v = new Variable();
    }
}

When does the variable "v" gets created every time for the 2nd scenario? Is the 2st scenario is equivalent to the 3rd one?

Upvotes: 1

Views: 396

Answers (3)

cRichter
cRichter

Reputation: 1411

Scenario 1: the variable v is intialized on every request, when page load happens, and there is no post back. (otherwise null)

scenario 2: the variable v is initialized on every instantiation of the class A, bevore the constructor is called.

scenario 3: the variable v is intialized on every request, when page load happens.

comment: if you access the variable v only after page load happens, then scenario 2 & 3 can be treated equal.

Upvotes: 2

James Curran
James Curran

Reputation: 103485

"It is created when the Page object is created which must occur before any events or methods of the object can be called." and "Sort-of. The creation is delayed a bit longer in the 3rd"

Upvotes: 0

Mitchel Sellers
Mitchel Sellers

Reputation: 63126

In your example the variable is always there at the same point, it is a private member of class A.

The initialization point is the difference between your example 1, 2, and 3.

In example one if there is no other calls, v will be null at all times.

In example two, v will contain a reference to a default "Variable" object as soon as class A is referenced

In example three, v will be null up until the Page_Load call then will contain a reference to a default 'Variable' object after that.

Upvotes: 0

Related Questions