C# static Class

The c# static class is same as other non-static classes, but it does not allow to create an instance of it. We can not create the object of a static class using the new keyword. Following is a simple static class Customer which contains a method PrintCustomer. The PrintCustomer is further being invoked using the class name.

Example

Try It
public static class Customer
{
    public static void PrintCustomer()
    {
        Console.WriteLine("Hello from PrintCustomber");
    }
}
public static void Main()
{
    Customer.PrintCustomer();
}

If the class is declared as static then it becomes necessary to declare the methods and variables of that class as static as well.

public static class Customer
{
    static string Name = string.Empty;
 
    public static string FirstName { get; set; } //The members must be static.
    public static string LastName { get; set; }
 
    public static void PrintCustomer()
    {
        Console.WriteLine("Hello from PrintCustomber");
    }
}

Inside a static class, instance variables can't be declared.

public static class Customer
{
    string Name = string.Empty; //Can not declare instance variables in a static class.
 
    public string FirstName { get; set; } //Can not declare instance variables in a static class.
    public string LastName { get; set; }  //Can not declare instance variables in a static class.
}

.Net Framework throws a compile time error when an instance member found declared inside a static class.

The static class uses the private constructor, due to that fact it is not possible to create an object of a static class.

Customer customer = new Customer(); //Not Possible to create an object of a static class

A class can be declared as static if it is not required to associate the class members and methods with an object. The static class is often created to contain the utility methods.

Following are the important features of a static class.

  • Static class does not allow to create instance members.
  • A static class can have only static members and methods
  • If a class is declared as static then it becomes sealed also, Hence it is not possible to inherit a static class in another class except the object class.
  • The static class uses the private constructor, due to that fact it is not possible to initialize a static class.
  • To access the members of a static class the class name itself is used.