How to define C# 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;//w w  w. j a va2s.  c  om

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;/* w  w w.  ja  va  2  s  .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.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor