C# Static Fields
In this chapter you will learn:
- How to create static fields and why static fields are useful
- Example for references static field without instance
- A demo showing how to use static fields
Description
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.
Example
The following code references static field without instance.
using System;//from w w w .j av a2 s . co 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.
Example 2
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;/*from www. j ava 2 s .c o m*/
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:
- What is a method in a class
- Syntax to create a method
- Example for a method
- Note for method definition
- Assign value to local variable