ASP.NET – Global Variables

I know that global variables are bad… but sometimes you have to…

Until a couple of months ago I used the Application object. A student of mine asked me what the difference is between using the Application object and a static class with some nice typed properties?

I said: “I don’t know for sure, but I guess the static class lives only as long as the app domain is living, and the Application object lives “a bit” longer…”
Some tests and a bit of googling (definitely read this to know the details) revealed:


ap--delete
From MSDN
A key reason that the Application object exists in ASP.NET is for compatibility with classic ASP code

ap--check
Better is to create your own static class that exposes some static properties.

  • Typed (no casting)
  • Performance on accessing static members
  • Memory usage is less with static classes

 

PS
Accessing static members is generally faster (and less memory intensive, because you don’t need to have instance variables)

Thanks ReSharper for reminding me to make some members static!

 

PPS
Static and instance members of   C# Language Specification explains the difference

3 comments:

DINESH said...

how to use global variables in silverlight4 ???

Peter Gfader said...

Hi Dinesh,

What do you mean?

- Do you want to have an Silverlight client application wide global variable?
That should be easy by having a static class, or google for Singleton. Jon Skeet has a nice implementation on his blog


- Or a variable that is up-to-date even when you refresh the application?
Look at using Isolated Storage (Bing with Google)


.peter.gfader.
http://www.ssw.com.au
http://blog.gfader.com

windows 7 said...

Thanks for your posting, i am just a newbie in the internet business, need to learn a lot from the gurus

Post a Comment

Latest Posts

Popular Posts