C # static classes and static members

Keywords: C#

Static members:

Non static classes can contain static methods, fields, properties, or events. Static members can be called on a class even if no instance of the class is created. Static members are always accessed by class name, not instance name. Only one copy of the static member exists (regardless of the number of instances of the class created). Static methods and properties cannot access non static fields and events in their containing types. They cannot access instance variables of any object unless it is explicitly passed in method parameters.

A more typical approach is to declare a non static class with some static members (instead of declaring the entire class static). Two common uses of static fields are to keep a count of the number of instantiated objects, or to store values that must be shared among all instances.

Static methods can be overloaded, but they cannot be replaced, because they belong to a class and do not belong to any instance of the class.

Although fields cannot be declared as   static const, but   const   Fields are essentially static in their behavior. It is a type, not an instance of a type. Therefore, you can use the same for static fields   ClassName.MemberName   Representation to access   const   Field. No object instantiation is required.

C # does not support static local variables (that is, variables declared in method scope).

Can be used before the return type of a member   static   Keyword to declare static class members, as shown in the following example:

public class Automobile
    public static int NumberOfWheels = 4;

    public static int SizeOfGasTank
            return 15;

    public static void Drive() { }

    public static event EventType RunOutOfGas;

    // Other non-static fields and properties...

Static members are initialized before they are first accessed and before the constructor, if any, is called. To access a static class member, specify the location of the member using the name of the class instead of the variable name, as shown in the following example:

int i = Automobile.NumberOfWheels;

If the class contains static fields, provide static constructors that initialize them when the class loads.

Calls to static methods generate call instructions using Microsoft Intermediate Language (MSIL), while calls to instance methods generate   callvirt   Directive, which also checks for null object references. However, most of the time, the performance difference between the two is not significant.

In short: members decorated with static are called static members.

class Beauty
//Static field
public static string feature = "beauty";
//Static method
public static void SpendMoney()
Console.WriteLine("buy:Clothes, bags, cosmetics, shoes....");

Static members can only be called by classes

public static void Main(string[] args)
string name = Beauty.feature;

Distinguish between static members:

Static class

Static classes are basically the same as non static classes, but there is one difference: static classes cannot be instantiated. In other words, it cannot be used   new   Operator to create a variable of class type. Since there are no instance variables, you can use the class name itself to access members of a static class.

Static classes can be used as a convenient container for a set of methods that operate only on input parameters and do not have to get or set any internal instance fields.

Therefore, creating a static class is basically the same as creating a class that contains only static members and private constructors. Private constructors prevent class instantiation. The advantage of using static classes is that the compiler can check to ensure that no instance members are accidentally added. The compiler guarantees that instances of this class cannot be created.

Static classes are sealed and therefore cannot inherit. They cannot inherit from any class (except Object). Static classes cannot contain instance constructors. However, they can contain static constructors. If a non static class contains static members that need meaningful initialization, it should also define a static constructor.


The following is an example of a static class that contains two methods for converting temperatures from Celsius to Fahrenheit and from Fahrenheit to Celsius:

public static class TemperatureConverter
    public static double CelsiusToFahrenheit(string temperatureCelsius)
        // Convert argument to double for calculations.
        double celsius = Double.Parse(temperatureCelsius);

        // Convert Celsius to Fahrenheit.
        double fahrenheit = (celsius * 9 / 5) + 32;

        return fahrenheit;

    public static double FahrenheitToCelsius(string temperatureFahrenheit)
        // Convert argument to double for calculations.
        double fahrenheit = Double.Parse(temperatureFahrenheit);

        // Convert Fahrenheit to Celsius.
        double celsius = (fahrenheit - 32) * 5 / 9;

        return celsius;

class TestTemperatureConverter
    static void Main()
        Console.WriteLine("Please select the convertor direction");
        Console.WriteLine("1. From Celsius to Fahrenheit.");
        Console.WriteLine("2. From Fahrenheit to Celsius.");

        string selection = Console.ReadLine();
        double F, C = 0;

        switch (selection)
            case "1":
                Console.Write("Please enter the Celsius temperature: ");
                F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
                Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);

            case "2":
                Console.Write("Please enter the Fahrenheit temperature: ");
                C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine());
                Console.WriteLine("Temperature in Celsius: {0:F2}", C);

                Console.WriteLine("Please select a convertor.");

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
/* Example Output:
    Please select the convertor direction
    1. From Celsius to Fahrenheit.
    2. From Fahrenheit to Celsius.
    Please enter the Fahrenheit temperature: 20
    Temperature in Celsius: -6.67
    Press any key to exit.

  In short: classes modified with static are called static classes.

Static classes cannot be instantiated, so only static members or const decorated constants are allowed inside.

static class MyMath
//int length; //  Cannot contain non static members
static int length;
const int id = 10;
//void fun() {} / / cannot contain non static members
static int Abs()
return a > 0 ? a : -a;

Static class features:
1. Constants containing only static members and const modifiers.
2. Cannot be instantiated.
3. It is sealed. (it is sealed by default and cannot be decorated with sealed)
4. There are static construction methods (functions), but the static construction methods must be parameterless.

Static construction method

Static constructors are used to initialize any static data or to perform specific operations that need to be performed only once. The static constructor is called automatically before the first instance is created or any static member is referenced.

public sealed class Time
public static float dealTime;
static Time() //No access modifiers, no parameters, no overloads
dealTime = 0.04f; //If you do not write this sentence, the system will assign a default value to the static variable
Console.WriteLine ("static Time().");
class MainClass
public static void Main (string[] args)
Console.WriteLine ( Time.dealTime);
//output:static Time().

Deeply understand the differences between C# static classes and non static classes and static members

Static class

The important difference between static classes and non static classes is that static classes cannot be instantiated, that is, variables of static class types cannot be created with the new keyword. Using the static keyword when declaring a class has two meanings: first, it prevents programmers from writing code to instantiate the static class; Second, it prevents any instance fields or methods from being declared inside the class.

Static classes have been introduced since C# 2.0. C# 1.0 does not support static class declarations. The programmer must declare a private constructor. Private constructors prohibit developers from instantiating instances of a class outside the scope of the class. The effect of using a private constructor is very similar to that of using a static class.

The difference between the two:
The private constructor method can still instantiate a class from within the class, while the static class prohibits instantiating a class from anywhere, including from within the class itself. Another difference between static classes and classes using private constructors is that instance members are allowed in classes using private constructors, while C# 2.0 and later compilers do not allow static classes to have any instance members. The advantage of using static classes is that the compiler can perform checks to ensure that instance members are not accidentally added, and the compiler will ensure that instances of this class are not created. Another feature of a static class is that the C# compiler automatically marks it sealed. This keyword specifies the class as non extensible; In other words, no other class can be derived from it.

Main features of static classes:
1: Contains only static members.
2: Cannot instantiate.
3: It's sealed.
4: Cannot contain instance constructors.

Static member  

1: Non static classes can contain static methods, fields, properties or events;
2: No matter how many instances of a class are created, its static members have only one copy;
3: Static methods and properties cannot access non static fields and events in their containing types, and cannot access instance variables of any object;
4: Static methods can only be overloaded, not overridden, because static methods do not belong to instance members of classes;
5: Although fields cannot be declared as static const, the behavior of const fields is static in nature. Such a field belongs to a class, not an instance of a class. Therefore, the const field can be accessed using the ClassName.MemberName notation as static fields;
6: C # does not support static local variables (static variables defined inside methods).

  static constructor

1: Static classes can have static constructors, which cannot be inherited;
2: Static constructors can be used for static classes or non static classes;
3: The static constructor has no access modifier, no parameters, and only one static flag;
4: The static constructor cannot be called directly. Before creating a class instance or referencing any static member, the static constructor is executed automatically and only once.

be careful:  

1: Static classes always have a place in memory;
2: Non static classes are independent in memory after instantiation. Their variables will not be repeated and will be destroyed in time after use, so there will be no unknown errors. Static members are sensitive things in C # and should not be used when they are not fully confirmed;
3: It is recommended to use more generic classes (non static classes).

Use selection:  

When the defined class does not need to be instantiated, we use static classes; If you need to instantiate objects and inherit, you should use non static classes, and set the uniformly used variables and methods to static, so that all instance objects can be accessed.

Learning summary of C# static members and methods

Data members:

Data members can be divided into static variables and instance variables
Static members:

Static member variables are associated with classes and can be used as "common" variables in classes (a common expression). They do not depend on the existence of specific objects. They are accessed through class name, dot operator and variable name

Instance members:

Instance member variables are associated with objects. Accessing instance member variables depends on the existence of instances. When multiple instance objects exist, each data member of each object has its own independent set of storage space.

Function members:
Methods can be mainly divided into static methods and instance methods

Static method:

Static methods are methods that do not belong to specific objects. Static methods can access static member variables. Static methods cannot directly access instance variables. Instance variables can be passed to static methods as parameters when instance functions are called. Static methods cannot call instance methods directly, but can be called indirectly. First, create an instance of a class, and then call static methods through this specific object.

Instance method:

The execution of an instance method is associated with a specific object, and its execution requires the existence of an object. Instance methods can directly access static variables and instance variables. Instance methods can directly access instance methods and static methods. The access method of static methods is class name plus dot operator plus variable name. When multiple instance objects exist, there is not a copy of each specific instance method in memory, but all objects of the same class share a copy of each instance method (instance methods only occupy "one set" space).
If a member in a class is declared static, the member is called static. Generally speaking, static members belong to the class, while non static members belong to the instance of the class. Each time you create an instance of a class, you open up an area in memory for non static members. The static members of a class are owned by the class and shared by all instances of the class. No matter how many copies of this class are created, a static member occupies only one area in memory.

The life cycle problem of static member variables in C# class is when to create and destroy declared elements. The "lifetime" of elements is the time period that elements can be used. Variables are the only elements that have a lifetime; To this end, the compiler treats procedure parameters and function return values as special cases of variables. The lifetime of a variable represents the period of time it can retain values. The value of a variable can be changed during its lifetime, but the variable always retains some value.

Posted by SnakeO on Sat, 23 Oct 2021 00:25:47 -0700