SoFunction
Updated on 2025-03-06

Detailed usage examples of static in C#

Preface

static, unchanging, only one in a certain class and will not differ depending on the instantiation object.

static can modify classes, fields, properties, methods, etc.

If you want to call a method after adding static modification, you canClick it out directly through the class name, and there is no need to instantiate the class anymore.

1. 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 type cannot be created using the new keyword.

Using static keywords 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.

1. The main features of static classes:

  • Contains only static members.
  • Unable to instantiate.
  • The essence of a static class is an abstract sealed class, so it cannot be inherited or instantiated.
  • Cannot include instance constructors.
  • If all members under a class need to be shared, then this class can be defined as a static class.

2. The difference between static classes and private constructors:

  1. The private constructor approach can still instantiate classes from inside a class, while static classes prohibit instantiating classes from anywhere, including from inside the class itself.
  2. In classes that use private constructors, instance members are allowed, and the compiler does not allow static classes to have any instance members.
  3. The advantage of using static classes is that the compiler can perform checks to ensure that instance members are not added by chance, and the compiler will ensure that instances of such classes are not created.
  4. The C# compiler will automatically mark it as sealed. This keyword specifies a class as non-extensible; in other words, other classes cannot be derived from it.

2. Static members

  1. Modification by static keywords is a class and instance members belong to the object. When this class is loaded for the first time, all static members under this class will be loaded.
  2. Static members are created only once, so there is only one static member, and the instance members have as many objects as they have.
  3. When the class is loaded, all static members will be created in the "static storage area". Once created, they will not be recycled until the program exits.
  4. When members need to be shared and methods need to be called repeatedly, these members can be defined as static members.
  5. In static methods, instance members cannot be called directly, because when the static method is called, the object may not exist.
  6. The this/base keyword cannot be used in static methods because it is possible that the object does not exist yet.
  7. You can create an object of this class and formulate the members of the object to operate in static methods.
  8. In the instance method, a static member can be called because the static member must exist at this time.
  9. A non-static class can contain static methods, fields, properties, or events;
  10. No matter how many instances are created for a class, its static members have only one copy;
  11. Static methods and properties cannot access non-static fields and events in their containing types, and cannot access instance members of any object;
  12. Static methods can only be overloaded, but not overridden, because static methods do not belong to instance members of the class;
  13. Although fields cannot be declared as static const, the behavior of const fields is essentially static. Such fields belong to the class, not to the instance of the class.

3. Static method

  • Static methods are methods that do not belong to specific objects;
  • Static methods can access static members;
  • Static methods cannot directly access instance members. In the case of instance function calls, instance members can be passed to static methods as parameters;
  • Static methods cannot directly call instance methods, but can be called indirectly. First, you need to create an instance of a class, and then call the static method through this specific object.

4. Static constructor

  • Static classes can have static constructors, and static constructors are not inheritable;
  • Static constructors can be used for static classes or non-static classes;
  • The static constructor has no access modifier or parameters, and only has one static flag;
  • Static constructors cannot be called directly. The static constructor is automatically executed and only once before creating a class instance or referring to any static member.
class Program
 {
         public static int i =0;
         public Program()
         {
             i = 1;
             ("Instance constructor is called");
         }
         static Program()
         {
             i = 2;
             ("The static constructor is executed");
         }
         static void Main(string[] args)
         {
             ();//The result is 2. First, the class is loaded, and all static members are created in the static storage area. i=0, and then the class members are called. At this time, the static constructor will be called, i=2             Program p = new Program();
             ();//The result is 1. After the strength is achieved, the instance constructor is called, i=1. Because the static constructor is only executed once, it will not be executed again.         }
 }

5. Static member storage

Use the static modifier to declare a static member belonging to the type itself rather than to a specific object

The static modifier can be used for classes, fields, methods, properties, operators, events, and constructors, but cannot be used for types other than indexers, destructors, or classes.

5.1 Static global variables

definition:

Before the global variable, add the keyword static. The variable is defined as a static global variable.

Features

  • This variable allocates memory in the global data area.
  • Initialization: If not explicitly initialized, it will be implicitly initialized to 0.

5.2 Static local variables

definition

In the localvariableWhen the static keyword is added before it, static local variables are defined.

Features

  • This variable allocates memory in the global data area.
  • Initialization: If not explicitly initialized, it will be implicitly initialized to 0.
  • It always resides in the global data area until the program runs. However, its scope is a local scope. When the function or statement block that defines it ends, its scope ends.

5.3 Static data members

Memory allocation:

Allocate in the global data area of ​​the program.

Initialization and definition:

  • Space must be allocated when static data members are defined, so they cannot be defined in class declarations.
  • In order to avoid repeated definitions in multiple source files using this class, the location cannot be defined in the class header file.
  • Static data members must exist as the program starts running, so the optimal location for their initialization is implemented inside the class.

Features:

  • The impact on the public, protected, private keywords is the same as that of ordinary data members.
  • Because its space is allocated in the global data area and is shared by all objects of this class, it does not belong to a specific class object. Its scope is visible when the class object is not generated, that is, when there is no instance of the class, we can operate it.

Access form:

Class object name. Static data member name

effect:

Static data members are mainly used on properties that all instances of the class have.

For example, for a deposit class, the account is different from each instance, but the interest rate for each instance is the same. Therefore, interest should be set as a static data member of the deposit class.

This has two benefits. First, no matter how many deposit-class objects are defined, the interest data members share the memory allocated in the global area, so they save storage space.

Second, once the interest needs to be changed, as long as it is changed once, the interest of all deposit-type objects will be completely changed, because they actually share the same thing.

5.4 Static member functions

Features

  • Static member functions are associated with classes, not with class objects.
  • Static member functions cannot access non-static data members. The reason is simple, non-static data members belong to specific class instances.

effect

Mainly used for operations on static data members.

Call form

Class object name. Static member function name ()

class Program
    {
        static int i = getNum();
        int j = getNum();
 
        static int num = 1;
 
        static int getNum()
        {
            return num;
        }
 
        static void Main(string[] args)
        {
            ("i={0}", i);
            ("j={0}", new Program().j);
            ();
        }
 
    }

Analyze the above code

("i={0}", i);

Here i is a static variable. When the class Program is loaded for the first time, memory must be allocated for all static variables in the Program. Although there is now hyperthreading technology, instructions are logically executed from top to bottom in order, so first allocate memory for static int i, and keep the default value of int in that memory 0, and then allocate memory for static int num variable, and of course the value is 0.

Then the second step is to assign values ​​to the variable: first assign values ​​to the static int i variable, i=getNum(), look at the code in getNum(), which is return num. At this time, the value of num is 0, so i=0. Then assign a value to the variable num, num=1; after this line of code is executed, num will be 1. So, j=1.

So the final result is:

i=0

j=1

Notice:

When the class is loaded for the first time, the static variables in the class will be allocated in order first. After all the memory space is allocated, the static variables will be assigned in order.

First divided into two parts: registers and memory (including cache)

Memory is divided into two parts: code and data

Data is divided into two parts: static storage area and runtime storage

Runtime storage is divided into stack and heap

Static storage is divided into global static storage and constants

Summarize

This is the end of this article about the detailed usage of static in C#. For more related content on the usage of C# static, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!