Static members in C #, static methods, static classes, and instance members (excerpt from someone else's article)

Source: Internet
Author: User

Article Directory

1. Static members, instance members

2. Static Class

3. Differences between static and non-static members of a class

--------------------------------------Split Line---------------------------------------------

1. Static members, instance members

1.1 Definition and description

Data members:

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: Static methods: Static methods are methods that are not part of a particular object, static methods can access static member variables and static methods, static methods can not directly access instance variables and instance methods, can be indirectly called, first to create an instance of a class, and then through this particular object to invoke the static method;

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 access static and instance variables directly, and 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).

Access rights table for static methods and instance methods
Static member variables Static methods Instance member variables Instance method
Static methods Direct access Direct access No direct access No direct access
Instance method Direct access Direct access Direct access Direct access

In short: the existence of an instance method must exist for an object instance, and if the object instance does not exist, the instance method does not call its owner. The existence of a static method is premised on the existence of the class, so there is no need to declare and new objects.

1.2 Code Demo

Classprogram{Staticvoid Main (String[] args) {class1.callobjectfunc ();//Static callConsole.WriteLine (Environment.NewLine); Class1 Tmpclass =New Class1 ();//instance invocationTmpclass.objectfunc (); Console.readkey (); }}Classclass1{Staticint class_m =9;//Static membersPrivateint object_m =8;//Instance membersPublicStaticvoidCallobjectfunc () {Console.WriteLine ("------------The static method call begins:"); Class1 Class1 =NewClass1 (); Class1. Objectfunc (); Console.WriteLine ("Object_m: "+ class1.object_m.ToString ()); Console.WriteLine ( "------------static method call Ends: " ); } public void Objectfunc () {Console.WriteLine ( " instance method call begins:  "); Console.WriteLine ( "class_m:  "+ class_m.tostring ()); Console.WriteLine ( " instance method call Ends:  ");}         
View Code

Output Result:

2. Static Class

A class can be declared as static to indicate that it contains only static members. You cannot use the New keyword to create an instance of a static class.For example, it is a common requirement to create a set of methods that do not manipulate instance data and are not associated with specific objects in your code. You should use static classes to include those methods.

The main functions of static classes are as follows:

    • They contain only static members. ----function members and variables must have a static modifier

    • They cannot be instantiated.

    • They are sealed. Sealed markup is automatically generated-----------compiler compile

    • They cannot contain instance constructors.

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 is able to perform checks to ensure that instance members are not accidentally added. The compiler will guarantee that this class will not be created for real profit.

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.

Static class:

Class companyinfo{"CompanyName" "    companyaddress";}}    
View Code

3. Differences between static and non-static members of a class

3.1 Differences

(1) Syntax differences: Static members have the keyword static, non-static members without the static modification;

(2) Storage differences: Static member variables stored in the program's global variable store, its scope is limited to the inside of the class, and throughout the program run only in memory to have a storage location, will not copy is not copied, just one;

Non-static member variables are stored in the variable store of the object, and multiple objects have multiple variables stored, only the objects that belong to them

(3) Attribution difference: the static member belongs to the class, is the property of the class, regardless of how many instances of a class are created, its static members have only one copy, and changes in each place will change its value;

A non-static member is subordinate to its object, and the change of the same non-static member value of the respective object does not affect each other, and how many copies the instance has;

(4) Life cycle difference: Know the difference between the storage location is not difficult to understand the difference between the life cycle, static members as long as the allocation of space in the entire program during the run, it is present, only after the program is closed, its memory will be collected by the GC collector, but the scope is still limited to the inside of the class, Calls outside of the class need to be accessed using the class name add-on;

The lifetime of a non-static member of a class follows the lifetime of the object, and the object dies and the non-static members are recycled;

(5) The difference in initialization order: initialization is the first static member of the class to initialize, then the non-static data member.

3.2 Code:

What is the output of the following code? Think of yourself first.

UsingSystem;UsingSystem.Collections.Generic;UsingSystem.Linq;UsingSystem.Text;Classclass1{PrivateStaticint i =Getnum ();PrivateStaticint num =1;Int J =Getnum ();PrivateStaticIntGetnum () {return num;} static void Main (string< Span style= "COLOR: #000000" >[] args) {Console.WriteLine ( " i={0} ", I); Class1 class1object = new Class1 ();   default constructor Console.WriteLine (j={0} " "i={0}  ", I); Console.readkey (); }} 
View Code

The output is:


Well, what's going on here? Will not be the same as you think, if you really have this idea, you still need to see my analysis below OH

Code Analysis

Class structure: This class has three variables, two private static member variables I and J, a non-static member variable num; a private static function Getnum (), a function entry main ()

Program execution Process: First of all, the initialization initializes the static variables of the class first.

I allocate space and initialize the value to 0-->num allocate space and initialize it to 0-->i assignment (call getnum function, at this time num is 0, return value is 0, so i=0)-->num assignment to 1-->main function

As for the main function, why is the I output not 1? This is because the static member is initialized only once, so calling I does not call the Getnum () function to assign a value at this point, and the call I is to get the value on the I allocation space.

(Outside: The person of the beginner program is not clear about the concept of variable declaration, allocation space and assignment, C # is a strongly typed language, the allocation of space is to assign variables to the variable before the type modifier space size, int allocates four bytes, char allocates 1 bytes, about the declaration and assignment is not in the scope of this article, Readers can self-Baidu)

Static members in C #, static methods, static classes, and instance members (excerpt from someone else's article)

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.