Define variable as static - changes even launching new browser

J

Johnny Luner

I have a base class (root.cs) and all my pages inherits from it. When I
access default_1.aspx, it changes the base class variable intentionally.
Now, when I close the browser launch a new I.E. to access default_2.aspx,
it shows "changed!!" on my screen! I assume launching new browser would
start a new instance everything. Can anyone explain why? thanks...

------------------------------------------------------------
root.cs (this file is compiled and put in /bin directory)
------------------------------------------------------------

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace company {
public class main : Page {
public static String my_string = "hello world";
}
}

------------------------------------------------------------
default_1.aspx
------------------------------------------------------------
<%@ Page Inherits="company.main" %>
<script language="c#" runat="server">
void Page_load(Object sender, EventArgs e) {
my_string = "changed!!!";
}
</script>
 
J

Jon Skeet [C# MVP]

Johnny Luner said:
I have a base class (root.cs) and all my pages inherits from it. When I
access default_1.aspx, it changes the base class variable intentionally.
Now, when I close the browser launch a new I.E. to access default_2.aspx,
it shows "changed!!" on my screen! I assume launching new browser would
start a new instance everything. Can anyone explain why? thanks...

Why would you expect starting a new browser to create a new a static
variable? A static variable belongs to the type - it has no concept of
a session or anything like that. You have one variable for as long as
the type sticks around. When the AppDomain is unloaded and reloaded,
that'll be a new variable - but until then, you'll have the one shared
variable.

It sounds like you're *really* after session data - look it up in an
ASP.NET tutorial.
 
J

Johnny Luner

Thanks!! that helps..


Jon Skeet said:
Why would you expect starting a new browser to create a new a static
variable? A static variable belongs to the type - it has no concept of
a session or anything like that. You have one variable for as long as
the type sticks around. When the AppDomain is unloaded and reloaded,
that'll be a new variable - but until then, you'll have the one shared
variable.

It sounds like you're *really* after session data - look it up in an
ASP.NET tutorial.
 
D

Dilip Krishnan

Static variables by definition are a single instance for the scope of
the *type*. They are not object instances. Hope that helps
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top