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

I see that I can write:

protected static 

in my C # class (in my case aspx.cs). As well as:

 private static 

What does it mean? Static is available everywhere. Why protection / privacy?

+13
c #
source share
7 answers

The definition of statics is not "available everywhere." This is a variable divided by the type declared inside the AppDomain scope.

Access modifiers do not change this definition, but explicitly affect the amount of access.

You are misleading the static modifier with access modifiers. A static variable still requires some accessibility. In your example, private static variables are available only in the type in which it is defined, protected will be available in the type and any derived types.

Remember that IIS (ASP.NET Application Hosting) processes workflows that will clear any static variable values ​​that are currently alive.
+25
source share

Static is a modifier. Both secure and private are access modifiers. The access modifier determines the scope of the variable. The static modifier is used when we want the field or method to be singleton, so we don’t need to access them when creating the object, rather we can call them directly through the class name

+3
source share

If you declare a variable as private, then you cannot access it outside the current class, and if you declare it as protected, then only the derived class will be able to access this variable. In your example, the main value of private and Protected does not change, so it does not matter how you declare it static or simple ...

 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 the above code, you can see if we want the static variable to be available only in the current class, then you need to make it as private.

+2
source share

One use is to create private static fields and open using public static methods / properties (to apply some custom business logic like singleton, etc.)

+1
source share

private
Only a code in the same class or structure can access a type or member.
protected
Only a code in the same class or structure or in a derived class can access a type or member. Static modifier
Static methods are called without reference to an instance.

+1
source share

static does not mean that it is available everywhere. You still need protected / private to determine visibility.

0
source share

Use protected if you want the variable to be accessible through certain classes, for example, when using polymorphism and inheritance. The publication makes it always visible within the scope, and the particular is pretty obvious.

0
source share

All Articles