Tuesday, March 13, 2012

Should I save changing of WebForm variables to Session variables?

Global.asax.cs
protected void Session_Start(Object sender, EventArgs e){ int a=0; Session["a"]=a;}
WebForm1.aspx.cs
public class WebForm1 : System.Web.UI.Page{ public int a; private void Page_Load(object sender, System.EventArgs e) { a=(int)Session["a"]; } private void Button1_Click(object sender, System.EventArgs e) { a=a+1; //should I save this changing to Sassion["a"] or It saves automaticaly?
}}
Now, someone may need to double-check this, but the cast to int shouldmake a copy of the variable in method scope, so therefore it wouldn'tupdate the session variable.
try it out and see... I'll check the docs shortly

Atrax wrote:

Now, someone may need to double-check this, but the cast to int should make a copy of the variable in method scope, so therefore it wouldn't update the session variable.
try it out and see... I'll check the docs shortly


It isn't specifically the cast to int that makes a copy of the value, rather the assigning of the value and not the reference to the address in memory (i.e. pointers).
And, just to confirm, the Session variable wouldn't be updated.

x4444 wrote:

Global.asax.cs

protected void Session_Start(Object sender, EventArgs e){ int a=0; Session["a"]=a;}
WebForm1.aspx.cs
public class WebForm1 : System.Web.UI.Page{ public int a; private void Page_Load(object sender, System.EventArgs e) { a=(int)Session["a"]; } private void Button1_Click(object sender, System.EventArgs e) { a=a+1; //should I save this changing to Sassion["a"] or It saves automaticaly?
}}


This isn't meant as a criticism but it seems, to me at least, rather unnecessary to create variables when you don't need to. For example:
Global.asax.cs
protected void Session_Start(Object sender, EventArgs e){ Session["a"]=0;}
WebForm1.aspx.cs
public class WebForm1 : System.Web.UI.Page{ private void Button1_Click(object sender, System.EventArgs e) { ((int) Session["a"])++;
}}













0 comments:

Post a Comment