tags:

views:

35

answers:

3

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?

A: 

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.

Mitchel Sellers
A: 

"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"

James Curran
+2  A: 

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.

cRichter
+1 for mentioning v is null on scenario 1 on post backs. This is an important difference.
senloe