C # static classes and static class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to detach data and behavior that are independent of any object identity: No matter what changes the object has, the data and functions do not change. Static classes can be used when there is no data or behavior that relies on the identity of the object in the class.
Let's take a look at static classes:
A class can be declared static to indicate that it contains only static members. You cannot use the New keyword to create an instance of a static class. A static class is loaded automatically by the. NET Framework Common Language Runtime (CLR) when the program or namespace that contains the class is loaded.
Use static classes to include methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not manipulate instance data and are not associated with specific objects in your code. You should use static classes to include those methods.
The main functions of static classes are as follows:
1, they contain only static members.
2, they cannot be instantiated.
3, they are sealed.
4, they cannot contain instance constructors (C # Programming Guide).
Therefore, creating a static class is roughly the same as creating a class that contains only static members and private constructors. The private constructor prevents the class from being instantiated.
The advantage of using static classes is that the compiler can perform checks to ensure that instance members are not accidentally added. The compiler will guarantee that no such benefit is created.
Static classes are sealed and therefore cannot be inherited. A static class cannot contain constructors, but you can still declare a static constructor to assign an initial value or set a static state.
When to use static classes
Suppose you have a class CompanyInfo that contains the following methods for obtaining information about company names and addresses.
class CompanyInfo
{
public string GetCompanyName() { return "CompanyName"; }
public string GetCompanyAddress() { return "CompanyAddress"; }
//...
}