1: static classes are only used to include static members and cannot be instantiated. We can directly use their attributes and methods. The biggest feature of static classes is sharing. Static classes prevent inheritance and new classes from external sources. It is equivalent to a sealed abstract class.
2: static classes and 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 separate data and behavior independent of any object identifier: No matter what changes occur to the object, the data and functions will not change. When the class does not depend on the data or behavior of object identifiers, you can use static classes.
3: the class can be declared as static to indicate that it only contains static members. You cannot use the new keyword to create a static class instance. When a static class loads a program or namespace containing the class, it is automatically loaded by the. NET Framework Common Language Runtime Library (CLR.
4: use static classes to include methods not associated with specific objects. For example, it is common to create a group of methods that do not operate on instance data and are not associated with a specific object in the code. You should use static classes to include those methods.
5. The main functions of static classes are summarized as follows:
They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain instance Constructors (C # programming guide ).
Static classes cannot use abstract or sealed modifiers.
Static classes are inherited from the system. Object root class by default, and cannot explicitly specify any other base classes.
Static classes cannot specify any interface implementation.
A static class member cannot have a protected or protected internal access protection modifier.
6: Therefore, creating a static class is roughly the same as creating a class that only contains static members and private constructor. Private constructors and virtual base classes prevent classes from being instantiated. As follows:
Class timeutilclass
{
// Redefine the default ctor as private to prevent creation.
Private timeutilclass (){}
Public static void printtime ()
{
Console. writeline (datetime. Now. tow.timestring ());
}
Public static void printdate ()
{
Console. writeline (datetime. Today. tow.datestring ());
}
}
// Define type as abstract to prevent creation
Abstract class timeutilclass
{
Public static void printtime ()
{
Console. writeline (datetime. Now. tow.timestring ());
}
Public static void printdate ()
{
Console. writeline (datetime. Today. tow.datestring ());
}
}
The advantage of using static classes is that the compiler can perform checks to prevent accidental addition of instance members. The compiler will ensure that such benefits will not be created.
Characteristics and usage of static classes