The use of static statically variable in C #

Source: Internet
Author: User
Tags garbage collection instance method static class advantage
Static global Variables

Definition: Before the global variable, with the keyword static the variable is defined as a static global variable.

Characteristics:
A, the variable allocates memory in the global data area.
B, initialization: If not explicitly initialized, it will be implicitly initialized to 0. Static Local Variables

Definition: Static local variables are defined when the static keyword is preceded by a local variable.

Characteristics:
A, the variable allocates memory in the global data area.
B, initialization: If not explicitly initialized, it will be implicitly initialized to 0.
C, it always resides in the global data area until the program has finished running. But its scope is a local scope, and when the function or statement block that defines it ends, its scope ends. static data members

Characteristics:
A, memory allocation: Allocated in the program's global data area.
B, initialization and definition:
A, static data member definition to allocate space, so cannot be defined in the class declaration.
b, to avoid repeating definitions in multiple source files that use the class, it cannot be defined in the header file of the class.
c, static data members are required to exist because the program starts running, so the best place to initialize it is implemented inside the class.
C, features
A, the impact on the Public,protected,private keyword it's the same as regular data members,
b, because its space is allocated in the global data area, it is shared by all objects of this class, so it is not a particular class object and its scope is visible when no class object is generated, that is, we can manipulate it without producing an instance of the class.
D, Access form
A, class object name. static data member name
E, static data members, mainly used on properties owned by all instances of the class. For example, for a deposit class, the account number is different from each instance, but the interest is the same for each instance. Therefore, interest should be set as a static data member of the deposit class. This has two advantages, first, regardless of how many deposit objects are defined, the interest data members share the memory allocated in the global area, so save storage space. Second, once the interest needs to change, as soon as the change is made, the interest of all the deposit objects changes over, because they are actually sharing one thing. Static member functions

Characteristics:
A, static member functions are associated with classes and are not associated with objects of the class.
B, static member functions cannot access non-static data members. The reason is simple, non-static data members belong to a particular class instance.
Role:
is primarily used for operations on static data members.

Call form:
Class object name. static member function name () example and analysis of static variable

class Class1
    {
        static int i = Getnum ();
        Int J = Getnum ();

        static int num = 1;

        static int Getnum ()
        {return
            num;
        }

        static void Main (string[] args)
        {
            Console.WriteLine ("I={0}", i);
            Console.WriteLine ("J={0}", new Class1 (). j);
            Console.read ();
        }
    

Analysis: Console.WriteLine ("I={0}", i); Here i is the static variable, and class Class1 is the first time to be referenced, to allocate memory for all the static variables in Class1 first. Although there is hyper-Threading technology Now, the instructions are executed sequentially in logic or one by one, so the static int i is first allocated memory, and the default value of 0 is maintained in that memory, and then the value of the static int num variable is then allocated to memory, of course, 0.

Then execute the second step, assign the value to the variable: first, the static int i variable assignment, i=getnum (), see the code inside the Getnum, is return num, this time num value is 0, so I was 0. Then assign value to the variable num, num=1, and after this line of code executes, NUM is 1.

So the final result is:

I=0 j=1

when you refer to a class at once, the static variables in the class are assigned the memory space sequentially, and after all the memory space is allocated, the static variables are assigned in order. What is the advantage of static. Why use static variables or functions ...

There are some things that are frequently used, and if you re new each time you use it, the overhead can be high, if you use static and keep it in memory, you want to use it directly, without having to recreate the data in a new piece of space. So the static is to implement a system caching function, its lifecycle until the application exit end.

Static members include static fields and static properties, static members and classes are associated, do not depend on the object and exist, can only be accessed by the class, not by the object;

Static members belong to class all, not to create how many instance objects, static members in memory only one; instance members belong to instances of the class, each instance object is created, and an instance member allocates an area of memory in memory.
So static members are typically used to store shared data segments, such as database connection strings.

If a class contains only static members and static methods, the class can be defined as a static class, with a static modifier for the class, a static method, and a non-static method:

First, the performance: static methods and instance methods are not very different. All methods, whether static or instance, are allocated memory when the class is JIT-loaded, and the static method is referenced by the class name, and the instance method refers to the object instance. When an instance is created, no memory is allocated for the method of the class, and all instance objects share the method code of a class. As a result, there is little difference in performance between static methods and instance method calls.

Static methods can only be accessed by the class, and instance methods can only be accessed by objects.

Advantages:
1, static variables loaded into memory when the class loads
2, so that the use of the New does not need to create all the objects in the class, you can call a method

Disadvantages:
1, garbage collection mechanism can not reclaim static variables, static class variables will be resident memory advantages and disadvantages of static classes in C # Disadvantages:

1. The entire type is loaded only once during the running of the program. This is for those types that are often used, so you don't have to load them before each use. Higher efficiency. But for the types that are not commonly used.
2, if it is a static type, it will occupy a considerable amount of memory, until the program stopped. Or the application domain is uninstalled. Therefore, you should only define static types for those commonly used types. Advantages:

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.

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: info-contact@alibabacloud.com 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.