C# Static Class

A static class is same as non-static class, but only difference is the static class cannot be instantiated. So you not use the new keyword to create the object of class.

Static class only contain static members, but the non-static class can contain both static and non-static members.

Static class Example

Using the static keyword you can define static class, also you can used static modifier with method, properties. etc See below example

public static class Student
{
    public static string name = "99Techguru";

    public static void DisplayName()
    {
        Console.WriteLine("Name = ", name);
    }
}

Use Static Method, Properties

You can use static method and properties without creating it's object. You can directly access through using class name followed by method or property. static method and static member can be initialized at run-time and for whole project only create one memory allocation for static member. See below example

class Program
{
    static void Main(string[] args)
    {
        Student.DisplayName();
    }
}

Static Constructor

A static constructor is used to initialize the static data members, and properties. See example below

static Student()
{
    name = "99Techguru";
}

Points to Remember

  • Static class cannot be instantiated.
  • Static class only access static members, non-static class contains both static and non-static members
  • Static members access without creating object of class, You can access static members direct class name with followed by methods and properties.
  • Static constructor is used to initialize the static data members, it can not contain any access modifiers and only define without arguments
  • Static variable and method can be initialized only once for whole project
  • Learn more about Static Class in Microsoft here