Information Technology Reference
In-Depth Information
Static Properties
Properties can also be declared
static
. Accessors of static properties, like all static members
Cannot access instance members of a class—although they can be accessed by them
Exist regardless of whether there are instances of the class
Must be referenced by the class name, rather than an instance name, when being
accessed from outside the class
For example, the following code shows a class with a static property called
MyValue
that is
associated with a static field called
myValue
. In the first three lines of
Main
, the property is
accessed, even though there are no instances of the class. The last line of
Main
calls an instance
method that accesses the property from
inside
the class.
class Trivial
{
static int myValue;
public static int MyValue
{
set { myValue = value; }
get { return myValue; }
}
public void PrintValue()
Accessed from inside the class
{
↓
Console.WriteLine("Value from inside: {0}", MyValue);
}
}
class Program
{
static void Main()
Accessed from outside the class
{
↓
Console.WriteLine("Init Value: {0}", Trivial.MyValue);
Trivial.MyValue = 10;
←
Accessed from outside the class
Console.WriteLine("New Value : {0}", Trivial.MyValue);
Trivial tr = new Trivial();
tr.PrintValue();
}
}
Init Value: 0
New Value : 10
Value from inside: 10