Saturday, 12 May 2012

static / Shared modifier in C# / VB.Net


static in C# or Shared in VB.Net

static - C# ( case sensitive ) / Shared in VB.Net is a modifier, with class scope. Member declared with this modifier cannot be accessed by the object of the class. This modifier is used with other Access Modifiers like private, public, internal, protected, and protected internal.

static / Shared variable gets the scope of application, not the current session of a specific user.

When we want to maintain application level data, we will use variables declared with this modifier.
Example: When we want to maintain the no of active users on our website, we will store the value in a static variable. Whenever a new user logs into the application we will increase the value or decrease it when one leaves.

We should not use this to maintain the data of a specific user.
Example: if we store the current user name in static variable at the time of login, and then it will always give the most recent logged in user name as current username.