1

Let's consider this page's code-behind:

public partial class Products : Page
{
    private static SomeClass SharedField;

    public Product()
    {
        // ... Some logic
    }
}

Do all Products pages instances share the same SharedField, I know this is a basic concept of static fields. But in this case, really? all users can have access (and can't have their own instance of) to the same static field on the website-level?

If so, in what aspects this would used by the web developer? or is this non-recommended practice?

Ken D
  • 5,880
  • 2
  • 36
  • 58

3 Answers3

2

SharedField will be available in one instance for the entire life-cycle of the web site.

To read a bit more about it, see this answer.

Community
  • 1
  • 1
Filip Ekberg
  • 36,033
  • 20
  • 126
  • 183
2

Yes, there will be a single instance of that static field for all users, but only within a single worker process. If you have web farms/web gardens, they will each have their own static instance. If the worker process restarts, you'll get a new static instance.

You'll have to use locking around that shared field to ensure thread safety.

As for why to use that, I'm not sure, I never do it. The best example I can give you is the built-in static HttpContext.Current, which gives you access to the Request, Response, etc.

Greg
  • 16,540
  • 9
  • 51
  • 97
0

A better practice would be to store your object in the Application state.

Application["MyObject"] = new SomeClass();

GavinH
  • 2,173
  • 1
  • 15
  • 17
  • Believe it or not, Microsoft says to use a static instead. http://stackoverflow.com/questions/4879023/what-is-the-life-span-of-a-field-in-a-static-class/4879119#4879119 – Greg Feb 09 '11 at 21:39
  • Wow, that really surprised me! I suppose the Application object has been superseded by the Cache object anyway. – GavinH Feb 09 '11 at 21:44