C# Static Fields

In this chapter you will learn:

  1. How to create static fields and why static fields are useful
  2. Example for references static field without instance
  3. 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:

  1. What is a method in a class
  2. Syntax to create a method
  3. Example for a method
  4. Note for method definition
  5. Assign value to local variable
Home »
  C# Tutorial »
    C# Types »
      C# Class Field
C# class field
C# Field default value
C# field initialization
C# Constant
C# Read only field
C# Static Fields