Sharing a variable between all pages

O

oliv

Hi,
New to .NET, I was wondering what was the proper way to share a
variable between all the instances of a web page.
I try with a static var, but it does not seem to always work. Why is
that ?


public partial class _Default : System.Web.UI.Page
{

static public string sharedvar;

protected void Page_Load(object sender, EventArgs e)
{
...

thanks
 
M

Marc Gravell

When you say "does not seem to always work" - what happens?

Either way, a static field is a risky proposition in a highly threaded
environment such as ASP.Net; at the very least this should be
protected by a property and synchronised between threads. There may be
more appropriate solutions: what are you trying to do with this var?
What does it hold?

Marc
 
G

Guest

This is probably more of an ASP.NET question than a C# language group one.
Typically in ASP.NET you would store your item either in Session,
Application, or Cache state depending on the business scenario or whether it
is user-specific.
Alternatively, you can put a public static field in your Global class
(global.asax) and you can then use it from any page with:

Global.MyItemName;

Peter
 
P

Peter Bradley

Yeah. The thing is, the Session is more for maintaining state across
different pages associated with the same Session. Perhaps the OP could
explain if these pages are sharing a Session - or if they are in different
Sessions (i.e. a second instance in a second browser instance on the same
client - or even two separate browser instances on different machines with
potentially different users). Until the OP gives us a bit more info about
what is required, it's hard to know what the exact nature of the problem is.


Peter
 
O

oliv

could you provide sample code for storing a var at an application
scope ? (not session scope)

(by "it does not seem to always work", I mean that the static var has
been set by some instance of the page, and another read a null value -
this behavior is different from java as to me)
 
J

Jay Warmack

Sounds like the Singleton pattern is in order here. Google 'Singleton
pattern in C#' and you should find countless examples of the middle tier
code required to implement the concept of global variables in a web or
windows form applcation.
 

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

Similar Threads

C# LINQ query problem (case insensitive) 2
Postback Question 2
ASP.Net C# - Class Advice 2
shell command 1
Simple question 4
invoke methods with params 7
Getting data from objects C# 1
Partial class problem 4

Top