This section describes C # static variables, including the use of static modifiers to declare C # static variables.
C # static variables are declared using the static modifier. They are created when the class is instantiated and accessed through the class. Variables without the static modifier are called as non-static variables. The static variable is created when the object is instantiated. The same C # static variable that accesses all instances of a class through the object is the same value, the same non-static variable of different instances of the same class can be different values. Non-static members, such as non-static variables and non-static functions, cannot be used in the implementation of static functions.
Using system;
Using system. Collections. Generic;
Using system. text;
Namespace example01
{
Class Program
{
Class class1
{
Public static String staticStr = "Class ";
Public String notstaticStr = "Obj ";
}
Static void Main (string [] args)
{
// Static variables are accessed by class. The same static variables of all instances of this class are the same value.
Console. WriteLine ("Class1's staticStr: {0}", Class1.staticStr );
Class1 tmpobj1 = new class1 ();
Tmpobj1.notstaticstr = "tmpobj1 ";
Class1 tmpobj2 = new class1 ();
Tmpobj2.notstaticstr = "tmpobj2 ";
// Non-static variables are accessed through objects. The same non-static variables of different objects can have different values.
Console. writeline ("tmpobj1's notstaticstr: {0}", tmpobj1.notstaticstr );
Console. writeline ("tmpobj2's notstaticstr: {0}", tmpobj2.notstaticstr );
Console. Readline ();
}
}
Output result: