All About Static

What is a static class?
 
A class which is decorated with the static keyword is a static class. A static class cannot be initialized using the new keyword. It class can only contain static members, instance members are not allowed in static class. 
 
Below is the example of a static class with static property,
  1. static class A {  
  2.     private static string _userName;  
  3.     public static string UserName {  
  4.         get {  
  5.             return A._userName;  
  6.         }  
  7.         set {  
  8.             A._userName = value;  
  9.         }  
  10.     }  
  11. }  
  • Static class cannot inherit any class and is implicitly sealed; i.e. any class cannot inherit static class. Static class can inherit only Object class. 

  • One can access static members as shown below,

    A.UserName 
Static Members 
   
Members which are declared by using static modifiers are static members as shown in the above example 
UserName property. They only belong to type not an instance of a class (Object). A static member can also declare inside a nonstatic class. One cannot access static member using this keyword. 
 
Important points about Static Members,
  1. Runtime Polymorphism is not possible with static members; i.e. one cannot declare static members as virtual.

  2. Only one instance of static members exist.
Static Constructor
 
Static Constructor is constructor which calls only once in the lifetime of the application and it is used to
initialize static fields. Static constructor exists for static for static and non-static class. For non-static
class, it is called before any instance constructor is created. One cannot use any access modifiers with
the static constructor.
 
The important point about the static constructor,     
  1. If an error occurs while calling static constructor then it is not invoked the second time and type will remain uninitialized for the lifetime of the application.

  2. The static constructor cannot have the parameter.