Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
Visual C#
C# Reference
C# Keywords
 static
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
C# Language Reference
static (C# Reference)

Updated: September 2008

The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes. The static modifier on a class means that the class cannot be instantiated, and that all of its members are static. A static member has one version regardless of how many instances of its enclosing type are created. For more information, see Static Classes and Static Class Members (C# Programming Guide).

The following class is declared as static and contains only static methods:

C#
static class CompanyEmployee
{
    public static void DoSomething() { /*...*/ }
    public static void DoSomethingElse() { /*...*/  }
}

A constant or type declaration is implicitly a static member.

A static member cannot be referenced through an instance. Instead, it is referenced through the type name. For example, consider the following class:

C#
public class MyBaseC
{
    public struct MyStruct
    {
        public static int x = 100;
    }
}

To refer to the static member x, use the fully qualified name (unless it is accessible from the same scope):

C#
Console.WriteLine(MyBaseC.MyStruct.x);

While an instance of a class contains a separate copy of all instance fields of the class, there is only one copy of each static field.

It is not possible to use this to reference static methods or property accessors.

If the static keyword is applied to a class, all the members of the class must be static.

Classes and static classes may have static constructors. Static constructors are called at some point between when the program starts and the class is instantiated.

NoteNote:

The static keyword has more limited uses than in C++. To compare with the C++ keyword, see Static (C++).

To demonstrate static members, consider a class that represents a company employee. Assume that the class contains a method to count employees and a field to store the number of employees. Both the method and the field do not belong to any instance employee. Instead they belong to the company class. Therefore, they should be declared as static members of the class.

This example reads the name and ID of a new employee, increments the employee counter by one, and displays the information for the new employee and the new number of employees. For simplicity, this program reads the current number of employees from the keyboard. In a real application, this information should be read from a file.

C#
    public class Employee4
{
    public string id;
    public string name;

    public Employee4()
    {
    }

    public Employee4(string name, string id)
    {
        this.name = name;
        this.id = id;
    }

    public static int employeeCounter;

    public static int AddEmployee()
    {
        return ++employeeCounter;
    }
}

class MainClass : Employee4
{
    static void Main()
    {
        Console.Write("Enter the employee's name: ");
        string name = Console.ReadLine();
        Console.Write("Enter the employee's ID: ");
        string id = Console.ReadLine();

        // Create and configure the employee object:
        Employee4 e = new Employee4(name, id);
        Console.Write("Enter the current number of employees: ");
        string n = Console.ReadLine();
        Employee4.employeeCounter = Int32.Parse(n);
        Employee4.AddEmployee();

        // Display the new information:
        Console.WriteLine("Name: {0}", e.name);
        Console.WriteLine("ID:   {0}", e.id);
        Console.WriteLine("New Number of Employees: {0}",
                      Employee4.employeeCounter);
    }
}
    /*
    Input:
    Matthias Berndt
    AF643G
    15
     * 
    Sample Output:
    Enter the employee's name: Matthias Berndt
    Enter the employee's ID: AF643G
    Enter the current number of employees: 15
    Name: Matthias Berndt
    ID:   AF643G
    New Number of Employees: 16
    */

This example shows that although you can initialize a static field by using another static field not yet declared, the results will be undefined until you explicitly assign a value to the static field.

C#
class Test
{
   static int x = y;
   static int y = 5;

   static void Main()
   {
      Console.WriteLine(Test.x);
      Console.WriteLine(Test.y);

      Test.x = 99;
      Console.WriteLine(Test.x);
   }
}
/*
Output:
    0
    5
    99
*/

For more information, see the following sections in the C# Language Specification:

  • 1.6.6.3 Static and instance methods

  • 5.1.1 Static variables

  • 10.3.7 Static and instance members

  • 10.5.1 Static and instance fields

  • 10.5.5.1 Static field initialization

  • 10.6.2 Static and instance methods

  • 10.7.1 Static and instance properties

  • 10.8.3 Static and instance events

  • 10.12 Static constructors

Date

History

Reason

September 2008

Clarified and updated text.

Customer feedback.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Singleton using static      Mujahid Khaleel   |   Edit   |   Show History
public class Singleton
{
    private static Singleton instance; //static Singleton instance variable to hold the object
 
    private Singleton() {}//Make it private so that users cannot use new to create new instance of this class
 
    public static Singleton GetInstance() //To create or access instance of this class user will call Singleton.GetInstance() static method
    {
        if(instance==null)
        {
            /*  If this is called for first time we will create new object of 
                Singleton and store it in instance variable else we will just 
                return the previously created instance.
            */
            instance = new Singleton();            
        }
        return instance;
    }
 
    public void DoSomeObjectWork()
    {
        //Sample method which can be invoked on object. 
    } 
}
Singleton using static - shorter version      Scott Rudy   |   Edit   |   Show History
  
// Here is a shorter form that relies on the CLR to acheive the same result.
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();

private Singleton() {}

public static Singleton GetInstance()
{
return instance;
}

public void DoSomeObjectWork() {}
}
The two examples here are not the same      Scott Havens   |   Edit   |   Show History
The first, by Mujahid Khaleel, employs a controlled lazy load, but is not thread safe in its current form -- in between the null instance check and assigning a new object to the static field, one or more other threads could assign to it as well. The second, shorter version, by Scott Rudy, provides less control in its lazy load, but is guaranteed to be threadsafe, as the runtime will only perform the 'private static readonly Singleton instance = new Singleton();' assignment once.
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker