Static modifier used with the class, field, method, properties, operator, event and constructors. We can not use static modifier with indexers, destructors.
When we use static modifier with the members then they are no more part of instance of a class. Static members are a part of class itself.
For example:
public class MyClass
{
public struct MyStruct
{
public static int x = 100;
}
}
//To refer to the static member x, use the fully qualified name
MyClass.MyStruct.x
Consider a class that represents a student. Assume that the class contains a method to count student. Both the method does not belong to any instance student. Instead they belong to the College class. Therefore, they should be declared as static members of the college class.
Static Class
If static modifier is apply to the class then all member of class must be static.
Classes, including static classes, may have static constructors.
It is not possible to make an instance of static class with “new” keyword.
Features of static class:
1. They can only contain static members.
2. They are sealed means we cannot inherit the class.
3. They can not contain non static constructors
Static Members and Constructor:
Static members are initialized before the static member is accessed for the first time.
A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
A static constructor does not take access modifiers or have parameters.
A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
Cheers!
Mahesh
maheshsingh21@hotmail.com