Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

I see I can write :

protected static

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

private static

What does it means? Static is accessible everywhere. Why protected/private?

like image 477
markzzz Avatar asked May 23 '12 08:05

markzzz


People also ask

Can we use protected static?

There's nothing wrong with a protected static field, as long as it's final . A mutable static field shared across classes is definitely cause for worry.

What's the point of private static?

Private static variables are useful in the same way that private instance variables are useful: they store state which is accessed only by code within the same class. The accessibility (private/public/etc) and the instance/static nature of the variable are entirely orthogonal concepts.

How do you access a private static variable?

A variable declared private static could easily be accessed, but only from the inside of the class in which it is defined and declared. It is because the variable is declared private, and private variables are not accessible outside the class. Within the class, they can be accessed using ClassName. Variable_name .

Can we use protected with static in Java?

Scenario:two classes (super class and subclass) in different packages. Super class has two protected methods,static and nonstatic method. Subclass using reference on superclass can "see" protected static method but cannot see non static protected method...


Video Answer


1 Answers

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.

like image 176
Adam Houldsworth Avatar answered Oct 20 '22 19:10

Adam Houldsworth