Deep understanding of C # static and non-static classes, static members of the difference

Source: Internet
Author: User
Tags terminates

Deep understanding of C # static and non-static classes, static members of the difference

Static class

The important difference between a static class and a non-static class is that a static class cannot be instantiated, that is, a variable of a static class type 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, and secondly, it prevents any instance fields or methods from being declared inside the class.

Static classes are introduced from C # 2.0, and C # 1.0 does not support static class declarations. The programmer must declare a private constructor. A private constructor prohibits a developer from instantiating an instance of a class outside the scope of the class. The effect of using a private constructor is very similar to the effect of using a static class.

The difference between the two: the private constructor mode can still instantiate the class from within the class, while static classes prohibit instantiating the class from anywhere, including from within the class itself. Another difference between static classes and the use of private constructors is that in classes that use private constructors, instance members are allowed, whereas C # 2.0 and later compilers do not allow any instance members of static classes. The advantage of using static classes is that the compiler is able to perform checks to ensure that instance members are not accidentally added, and the compiler will guarantee that instances of this class will not be created. Another characteristic of a static class is that the C # compiler automatically marks it as sealed. This keyword specifies that the class is not extensible, in other words, you cannot derive other classes from it.

Key features of static classes: 1: Contains only static members. 2: Cannot instantiate. 3: Is sealed. 4: Cannot contain instance constructors.

Static member 1: A non-static class can contain static methods, fields, properties, or events; 2: No matter how many instances are created on a class, 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 an instance variable of any object; 4: Static methods can only be overloaded, not overridden, because static methods do not belong to instance members of the class; 5: Although fields cannot be declared as static const, the behavior of a const field is inherently static. Such a field belongs to a class and does not belong to an instance of the class. Therefore, you can use classname.membername notation to access a const field as you would with a static field; 6:c# does not support static local variables (static variables are defined inside a method).

Static Constructor 1: A static class can have static constructors, static constructors are not inheritable, 2: Static constructors can be used for static classes, or non-static classes, 3: Static constructors No access modifiers, no parameters, only a static flag; 4: Static constructors cannot be called directly, and static constructors are executed automatically and only once when a class instance is created or any static member is referenced.

Note: 1: Static class in memory is always position, 2: Non-static class is in memory after instantiation is independent, its variables are not duplicated, after use will be destroyed in time, so there will be no unknown error. Static members in C # are relatively sensitive and do not use when not fully confirmed; 3: It is recommended to use more general classes (non-static classes).

Use selection: When the defined class does not need to be instantiated, we use static classes, and if you need to instantiate an object, you should use a non-static class when you need to inherit attributes such as, and the uniformly used variables and methods are set to static, then all instance objects can be accessed.

A summary of learning about static members and methods in C #

Data members: Data members can be divided into static variables, instance variables, two kinds. Static members: Static member variables are associated with a class and can be used as a "common" variable in a class (a commonality of expression), and he does not rely on the existence of a particular object, accessed by the name of the multibyte variable when it accesses the class name.

Instance member: an instance member variable is associated with an object, and accessing an instance member variable depends on the existence of the instance.

Function members: Methods can be mainly divided into static methods, example methods

Static methods: Static methods are methods that are not part of a particular object, static methods can access static member variables, static methods can not directly access instance variables, and in the case of instance function calls, instance variables are passed as arguments to static methods. A static method cannot invoke an instance method directly, it can be called indirectly, first to create an instance of a class, and then to invoke a static method through this particular object.

Instance method: The execution of an instance method is associated with a particular object, and his execution requires an object to exist. Instance methods can directly access static variables and instance variables, and instance methods can directly access instance methods, and static methods, and static methods access the multibyte variable names for the class name.   When multiple instance objects exist, there is not a copy of a particular instance method in memory, but all objects of the same class share a copy of each instance method (the instance method occupies only a "set" of space). If a member in a class is declared as static, the member is said to be a statically member. In general, static members are owned by the class, and non-static members belong to instances of the class. Every instance of creating a class creates an area in memory for non-static members. The static members of the class are all classes, shared for all instances of the class. No matter how many copies this class creates, a static member occupies only one area of memory.

The life cycle of static member variables in C # classes is when to create and when to destroy the "lifetime" of a declared element is the time period in which the element is available for use. A variable is the only element with a lifetime; for this reason, the compiler treats procedure parameters and function return values as special cases of variables. The lifetime of a variable indicates the time period at which it can retain a value. The value of the variable can be changed during the lifetime, but the variable always retains some value.

A different life cycle
Variables declared at the module level are usually present during the entire run of the application. A non-shared variable declared in a class or struct exists as a separate copy of each instance of the class or struct in which it is declared, and each such variable has the same lifetime as its instance. However, the Shared variable has only one lifetime, which is the total time that the application runs.

Local variables declared with Dim exist only when the procedure that declares them is executing. The same applies to the parameters of the procedure and any function return values. However, if the procedure calls other procedures, local variables retain their values while the called procedure is running.

The beginning of the life cycle

When you execute a procedure that declares a local variable, the lifetime of the local variable begins. As the procedure starts, each local variable is initialized to its default value for the data type. numeric variables (including Byte and Char) are initialized to the 0,date variable initialized to zero January 1 of A.D. 1, the Boolean variable is initialized to False, and the reference type variable (including string, array, and Object) is initialized to nothing.

Each member of a struct variable is treated as a separate variable initialization. Similarly, each element of an array variable is initialized separately.

If a variable is declared with an initializer, the variable is assigned the specified value when it executes the declaration statement for the variable, as shown in the following example:

Dim X as Double = 18.973 ' x had previously been initialized to 0. A variable declared in the inner block of a procedure is initialized to its default value when it enters the procedure. These initializations will take effect regardless of whether the block has been executed.

The end of the life cycle

When the procedure terminates, the local variable value of the procedure is no longer preserved, and the memory used by the local element is reclaimed. The next time the procedure is executed, all its local elements are recreated and the local variables are initialized.

When an instance of a class or struct terminates, its non-shared variables lose their value. Each new instance of a class or struct creates all of its non-shared elements and initializes non-shared variables. The Shared element is persisted until the application stops running.

Extension of life time

If a local variable is declared with the Static keyword, its lifetime is longer than the execution time of the procedure that declares it. If the process is within a module, the static variable persists as long as the application continues to run.

If the static variable is declared in the inner procedure of the class, the lifetime of the variable depends on whether the procedure is shared. If this procedure has been declared with the shared keyword, the lifetime of the variable will continue until the application terminates. If this procedure is unshared, its static variable is an instance member of the class, and its lifetime is the same as the lifetime of the class instance.

In the following example, the RunningTotal function calculates the total of traffic by adding a new value to the total of the previous value stored in the static variable ApplesSold:

Copy Code code example:Function RunningTotal (ByVal Num As Integer) As Integer Static ApplesSold As Integer ApplesSold = ApplesSold + num Return A Pplessold ' ApplesSold keeps its current value. End Function

If ApplesSold is declared without Static, the previously accumulated value is not preserved during the function call, and the function returns only the same value that was last used to invoke it.

Declaring ApplesSold at the module level can produce the same lifetime. However, if you change the scope of the variable in this way, the procedure will no longer have exclusive access to the variable. Because other procedures can access the variable and change its value, the traffic totals are unreliable, and the code can be more difficult to maintain.

Static members are initialized before being accessed for the first time and before any static constructors, such as calls. To access a static class member, you use the class name instead of the variable name to specify the location of the member.

Reference to this article:

Deep understanding of C # static and non-static classes, static members of the difference

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.