What can I do with a protected/private static variable?

The definition of static isn't "available everywhere". It is a variable shared across the type it is declared within in the scope of an AppDomain.

Access Modifiers do not alter this definition, but obviously affect the scope of access.

You are confusing the static modifier with access modifiers. A static variable still needs accessibility defined. In your example, private static variables are only accessible within the type it is defined in, protected would be accessible within the type and any derived types.

Just a note, be aware that IIS (hosting ASP.NET applications) recycles worker processes, which will flush any static variable values that are alive at the time.


If you declare a variable as a Private then you are not able to access it outside the current class and if declare as a Protected then only the derived class is able to access that variable..In your example the basic meaning of private and Protected is not changing so it does not matter how you declare it Static or simple one...

class Test
{
    protected static int var1;
    private static int var2;
}
class MainProgram : Test
{
    private static int test;
    static void Main(string[] args)
    {
        Test.var1 = 2;
        Test.var2 = 5;   //ERROR :: We are not able to access var2 because it is private                 
    }
}

In above code you can see if we want the static variable is accessible only in the current class then you need to make it as a Private.

Tags:

C#

.Net