Working with static in C#

C# Static Keyword

This article is about the static keyword in C# and how to use static in C# applications. This article covers what a static class is in C#, the purpose of static members, and how static is used in C#. You'll also learn about static constructors, static methods, and properties with examples of using static.

The static keyword can be applied to class members, including constructors, methods, properties, and events. Static can also be applied to classes. The static modifier makes a member non-instantiable. The class members can only be accessed via the class name (type).

Static members in C#

Static members in a C# class are declared using the static keyword before the member's name with other modifiers. The purpose of using static types is to have only one copy of a variable in memory. Therefore, the last value assigned to the member is reflected everywhere a static member is used.

A class is loaded when either

  • .The static members of the class are accessed for the first time, or
  • When the first instance of the class is created.
  • Once a class is loaded, it will remain in memory permanently, and all static members of that class.

For every new instance of a class, all the instance members are allocated memory as one unit, but static field members of a class are allocated memory only once, irrespective of the number of objects created, and they are allocated memory when the class is loaded. These members are also called class members and are accessed outside the class using the class name.

A public static member of a class can be used as a Global member of the application because it can be assessed using the class names from any part of the application.

Static Constructor in C#

  • It is a constructor with a static keyword.
  • It is used to initialize static members dynamically and is executed when the class is loaded.
  • It is invoked by the CLR when the class is loaded and hence cannot be overloaded nor declared with any accesses specifier like a public or private.

Series of events that occur when the first object is created,

  1. The class is loaded.
  2. Static members are loaded and allocated memory.
  3. A static constructor is executed.
  4. The object is created, and Instance members are loaded and allocated memory.
  5. Instance constructor is executed.
  6. 4 and 5 repeats for the subsequent objects.

Note

Static constructors cannot access Instance members of the class. This is because when the static constructor is executed, the instance members are not allocated any memory. Therefore, a static constructor can't be parameterized.

Static Methods

A method that does not have anything to do with the object's state can be marked as a static method. Static methods and properties can only access static fields and static events.

Here is an example:

class File {  
    public string srcPath;  
    public void Copy(string destPath) {...  
    }  
    public static void Copy(string srcPath, string destPath) {...  
    }  
}   

Note

All methods and properties (procedures) of the class, irrespective of whether they are static, are allocated memory for instructions only once. 

  1. Outside the class, static members of a class can be accessed using class names, whereas the instance member of a class must be accessed using a reference variable referring to an object of that class.
  2. Instance members of the class cannot be accessed in a static constructor or any other static method or property of the class (unless it is qualified by a reference variable referring to an object of that class).

For example,

public static void Foo() {  
    //this._Balance = 100; // Is Invalid  
    Accout a = new Account();  
    a._Balance = 100; // IsValid because _Balance is qualified by “a” which is reference to an object.  
} 
  1. An instance member can access static members of the class. 
  2. “this” cannot be used in the static member of a class.

Static Class

A class in C# can be declared as static; such a class can have only static members, and instance members are not allowed. Also, such a class cannot be instantiated. 

It is ideally used for managing Global data.

static class Demo {  
    public static int P1;  
    public static void Foo() {}  
}  

Example

If a static class contains non-static members, it gives an error.

Static In C#

 

Example program using a static keyword

A complete C# program uses a static class with static fields, static properties, a static constructor, and a static method.

using System;  
namespace Article__Static {  
    static class Program {  
        static string name;  
        private static string _subject;  
        public static string subject {  
            get {  
                return _subject;  
            }  
            set {  
                _subject = value;  
            }  
        }  
        static Program() {  
            Console.WriteLine("static constructor.");  
            name = "static member.”  
        }  
        public static void Display() {  
            Console.WriteLine("static method.” + name);   
            }  
            static void Main(string[] args) {  
                Program.subject = "CSharp";  
                Console.WriteLine(Program.subject);  
                Program.Display();  
            }  
        }  
    }  

Output

Static In C#

Summary

This article taught us all about the static keyword in C#. The C# static keyword is used to declare static classes, static members, static methods, and static properties. 


Recommended Free Ebook
Similar Articles