Scope of private static variable in non static class

Viewed 1302

I know that, a static property can persist its value as long as the application remains running. Will it be same for a private static field inside non static class

public class A
{
   private static int B;

   public int GetSession()
   {
     return B++;
   }
}

In above class i have a private static field. Will calling GetSession() method will provide number of times the GetSession() accessed?

3 Answers

Since B is static it'll be shared between all sessions; the thread-safe (what if two sessions are trying to access / increment it simultaneously?) implementation is

   public int GetSession()
   {
       return Interlocked.Increment(ref B);
   }

Edit: If we want to emulate B++, not ++B (and return B before incrementing - see Jeppe Stig Nielsen's comment) we can just subract 1:

   public int GetSession()
   {
       // - 1 Since we want to emulate B++ (value before incrementing), not ++B
       return Interlocked.Increment(ref B) - 1;
   }

Yes, it will provide the number of times the GetSession() method was called.

It will be the total over all instances of A.

Note that it is not thread safe, so if your application has multiple threads potentially calling GetSession() concurrently, the count may be wrong. See Dmitry Bychenko's answer. This is no problem if all your instances of A are being called from the same thread.

Also note, that if your application has several AppDomains, each AppDomain will have a separate static field. So then it counts only invocations from within the same AppDomain, regardless of which instance the calls went through.

Yes it will still return the number of times B was accessed. It's still static. Adding private does not change this. And making the class static means that an object cannot be instantiated for that class, therefore, everything in the class would need to be static. But the variable will still behave the same.

Related