Static Fields
In this chapter you will learn:
Create static fields
Variables declared as static are, essentially, global variables. All instances of the class share the same static variable. A static variable is initialized when its class is loaded. A static variable always has a value.
If not initialized, a static variable is initialized to
- zero for numeric values.
- null for object references.
- false for variables of type bool.
The following code references static field without instance.
using System;/*from j ava2 s . c o m*/
class MyClass
{
static public int myStaticValue;
}
class Program
{
static void Main()
{
MyClass.myStaticValue = 5;
Console.WriteLine("myStaticValue = {0}", MyClass.myStaticValue);
}
}
The code above generates the following result.
Demo usage for static fields
The following shows how to use static field to count class instance. Each time a new instance is created the count would plus one.
using System;/*j a v a 2s.c om*/
class MyClass
{
public MyClass()
{
instanceCount++;
}
public static int instanceCount = 0;
}
class MainClass
{
public static void Main()
{
MyClass my = new MyClass();
Console.WriteLine(MyClass.instanceCount);
MyClass my2 = new MyClass();
Console.WriteLine(MyClass.instanceCount);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Class