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,
- static class A {
- private static string _userName;
- public static string UserName {
- get {
- return A._userName;
- }
- set {
- A._userName = value;
- }
- }
- }
- 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,
- Runtime Polymorphism is not possible with static members; i.e. one cannot declare static members as virtual.
- 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,
- 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.
- The static constructor cannot have the parameter.