English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# static class, method, constructor, field

In C#, static represents content that cannot be instantiated. You cannot create an object of a static class, nor can you access static members using an object.

Classes, variables, methods, properties, operators, events, and constructors can be defined as static using the static modifier keyword.

Static class

Apply the static modifier before the class name and after the access modifier to make the class static. Below is defined a static class with static fields and methods.

public static class Calculator
{
    private static int _resultStorage = 0;
    
    public static string Type = "Arithmetic";
    public static int Sum(int num1, int num2)
    {
        return num1 + num2;
    {}
    public static void Store(int result)
    {
        _resultStorage = result;
    {}
{}

The above Calculator class is static. All its members are also static.

You cannot create an object of a static class. Therefore, you can access the static members of the class directly using ClassName.MemberName, as shown below.

class Program
{
    static void Main(string[] args)
    {
        var result = Calculator.Sum(10, 25); //Call static methods
        Calculator.Store(result); 
        var calcType = Calculator.Type; // Access static variables
        Calculator.Type = "Scientific"; // Assign a value to the static variable
    {}
{}

Static class rules

  1. Static classes cannot be instantiated.

  2. All members of a static class must be static. Otherwise, the compiler will give an error.

  3. Static classes can contain static variables, static methods, static properties, static operators, static events, and static constructors.

  4. Static classes cannot contain instance members and constructors.

  5. Indexers and destructors cannot be static

  6. var cannot be used to define static members. You must explicitly specify the member type after the static keyword.

  7. Static classes are sealed classes, so they cannot be inherited.

  8. Static classes cannot inherit from other classes.

  9. Static class members can be accessed using ClassName.MemberName (i.e., class name.member name).

  10. Static classes are retained in memory throughout the entire lifecycle of the application domain in which the program is located.

Static members in non-static classes

Regular class (non-static class) can contain one or more static methods, fields, properties, events, and other non-static members.

It is more practical to define some static members in a non-static class instead of declaring the entire class as a static class.

Static fields

You can use the static keyword to define static fields in non-static classes.

Static fields of non-static classes are shared among all instances. Therefore, changes made by one instance will reflect in other instances.

public class StopWatch
{
    public static int InstanceCounter = 0;
    // Instance Constructor
    public StopWatch()
    {
    {}
{}
class Program
{
    static void Main(string[] args)
    {
        StopWatch sw1 = new StopWatch();
        StopWatch sw2 = new StopWatch();
        Console.WriteLine(StopWatch.NoOfInstances); //2 
        StopWatch sw3 = new StopWatch();
        StopWatch sw4 = new StopWatch();
        Console.WriteLine(StopWatch.NoOfInstances);//4
    {}
{}

Static Method

You can define one or more static methods in a non-static class. Static methods can be called without creating an object. You cannot call static methods using an object of a non-static class.

Static methods can only call other static methods and access static members. You cannot access non-static members of the class in static methods.

class Program
{
    static int counter = 0;
    string name = "Demo Program";
    static void Main(string[] args)
    {
        counter++; // Static fields can be accessed
        Display("Hello World!"); // Static methods can be called
        name = "New Demo Program"; //Error: Cannot access non-static member
        SetRootFolder("C:\MyProgram"); //Error: Cannot invoke non-static method
    {}
    static void Display(string text)
    {
        Console.WriteLine(text);
    {}
    public void SetRootFolder(string path) { }
{}

Static Method Rules

  1. Static methods can be defined using the static keyword before the return type, followed by the access modifiers.

  2. Static methods can be overloaded but cannot be overridden.

  3. Static methods can contain local static variables.

  4. Static methods cannot access or call non-static variables unless they are explicitly passed as parameters.

Static Constructor

A non-static class can contain a parameterless static constructor. It can be defined using the static keyword without access modifiers, such as public, private, and protected.

The following example demonstrates the difference between the static constructor and the instance constructor.

public class StopWatch
{
    // Static Constructor
    static StopWatch()
    {
        Console.WriteLine("Called static constructor");
    {}
    // Instance Constructor
    public StopWatch()
    {
        Console.WriteLine("Called instance constructor");
    {}
    // Static Method
    public static void DisplayInfo()
    {
        Console.WriteLine("Called DisplayInfo");
    {}
    // Instance Method
    public void Start() { }
    // Instance Method
    public void Stop() { }
{}

The non-static class StopWatch contains a static constructor and also a non-static constructor.

The static constructor is called only once when using a static method or creating an instance for the first time. The following example shows that the static constructor is called when the static method is called for the first time. Calling the static method again will not call the static constructor.

StopWatch.DisplayInfo(); // Static constructor is called here
StopWatch.DisplayInfo(); // Constructor is not called here
Output:
Static constructor has been called.
Called DisplayInfo
Called DisplayInfo

The following example shows that the static constructor is called when an instance is created for the first time.

StopWatch sw1 = new StopWatch(); // First is the static constructor, then the instance constructor 
StopWatch sw2 = new StopWatch();// Only the instance constructor is called 
StopWatch.DisplayInfo();
Output:
Called static constructor
Called instance constructor
Called instance constructor
Called DisplayInfo

Static Constructor Rules

  1. The static constructor is defined using the static keyword without the use of access modifiers public, private, or protected.

  2. A non-static class can contain a parameterless static constructor. Parameterized static constructors are not allowed.

  3. Static constructors will only be executed once during their lifetime. Therefore, if a class is used in multiple places, it is not possible to determine when it is called in the application.

  4. Static constructors can only access static members. They cannot contain or access instance members.

Static members are stored in a special area of memory called '高频堆'. Static members of a non-static class are shared among all instances of the class. Therefore, changes made by one instance will reflect in all other instances.