Static variables:
Static variables are declared with the static modifier
Created when the owning class is loaded
Access through a class
The same static variable for all instances of the owning class is the same value
Non-static variables:
Variables not declared with the static modifier are called non-static variables
Created when a class is instantiated
Access through objects
The same non-static variable for different instances of the same class can be a different value
Example:
[Copy to Clipboard] CODE:
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)
{
A static variable is accessed through a class, and the same static variable for all instances of the class is 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, and the same non-static variable 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 ();
}
}
}
Results:
Class1 ' s Staticstr:class
TmpObj1 ' s notstaticstr:tmpobj1
TmpObj2 ' s NOTSTATICSTR:TMPOBJ2