Learn about Static Class in C#

Introduction

In C#, a class built using the static modifier is referred to as a static class. Only static members are allowed in a static class. A static class cannot have an instance created for it. This is because all of its members are static. We also know that utilizing the class name will allow us to access a class's static members.

public static class JaiminStaticClass 
{
	public static void PrintCurrentDateTime() 
	{
        		// You can call this method without instance needs
		Console.WriteLine(DateTime.UtcNow);
	}
}

Things to keep in mind with the static C# class

  • There are just static members in the C# static class.
  • It is not possible to instantiate a static C# class.
  • Static classes in C# are sealed.
  • Instance constructors are not allowed in C# static classes.

Features of the C# Static Class

Let's dive into the inner workings of C# static classes and explore what they have to offer.

Knowing how to use the static class constructor in C#

In C#, a static constructor initializes the type itself upon loading and is supported by a static class. Static constructors are similar to the ignition spark that ignites the engine of your bike or car.

public static class JaiminStaticClass 
{
	//Static constructor
	static JaiminStaticClass()
	{
		// Do you initialization code here
	}
}

Examining the C# static partial class in detail

The partial keyword is used to build a partial class.

One unique feature in C# is the partial class. It enables you to divide a single class's implementation across several files. These discrete files are integrated into a single class during the compilation process of your program.

While methods, properties, and events can be included in a static partial class, instance members are not permitted.

public static partial class JaiminStaticClass
{
    public static decimal Addition(decimal x, decimal y)
    {
        return x + y;
    }
}

public static partial class JaiminStaticClass
{
    public static decimal Subtraction(decimal x, decimal y)
    {
        return x - y;
    }
}
Console.WriteLine("{0} - {1}", nameof(JaiminStaticClass.Addition), JaiminStaticClass.Addition(10, 30));
Console.WriteLine("{0} - {1}", nameof(JaiminStaticClass.Subtraction), JaiminStaticClass.Subtraction(10, 30));

Static Method in abstract class C#

Abstract classes can have static methods.

This is justified by the fact that static methods are directly related to the class and do not function on instances.

public abstract class JaiminAbstractClass
{
    public static void Print()
    {
        Console.WriteLine("This is a abstract print method.");
    }
}

public class TestClass : JaiminAbstractClass
{
    public void Display()
    {
        Print();
    }
}
var testClass = new TestClass();
testClass.Display();

It will display the print message.

Keep in mind that you are unable to develop an abstract static method. In an abstract class, a non-abstract static method may be defined, though.

Utility functions and other class-level features are frequently implemented via static methods in abstract classes.

Static class inheritance in C#

Static classes are distinguished in part by their incapacity to function as base classes. This means that a static class cannot be inherited by another class.

Sealed vs Static classes in C#

Although it cannot function as a base class, a sealed class can have instances.

An inherited class is referred to as a sealed class. It has a clear seal of sealing.

A static class, on the other hand, is abstract and implicitly sealed.

Static classes group related functions without allowing instantiation, whereas sealed classes prevent inheritance.

public sealed class JaiminSealedClass 
{
	public int a;
	public int b;
}

public static class JaiminStaticClass 
{
    	public static void StaticMethod() 
	{
        	//Write code here
    	}
}

Static Variables

Static variables behave like a sponge that holds water until it is completely squeezed out; they hold their values until the program ends.

Static variable in non-static class C#

Yes, static variables can be used in non-static classes.

public class JaiminClass 
{
	// Declare the static variable in a non-static class
    	public static int cnt = 0;
}

Understanding Dependency Injection

Dependency Injection (DI) keeps components flexible, loosely connected, and unit-testable in the world of C#. It resembles a well-oiled machine of a team where every member knows their role and plays it without interfering with others.

Dependency injection in a static class

This can become complicated with dependency injection in static classes, so your best bet is to use a ServiceProvider.

public static class JaiminStaticClass 
{
	private static IServiceProvider _serviceProvider;

	public static void Configure(IServiceProvider serviceProvider) 
	{
		_serviceProvider = serviceProvider;
	}

	// Other property or methods...
}

Importance of Static Class in C#

Static classes are strong and useful and conceal a wealth of secrets, much like the hidden journal of C#.

Why use static classes in C#?

The use of static classes becomes necessary when objects are not at all necessary. It's similar to owning a tool that doesn't need to be used with a manual each time. Simply take it up and finish the task!

Why do we use static classes in C#?

The main reason we use static classes is because they remove the requirement to build an object in order to utilize variables or invoke methods. It's similar to operating an automatic vehicle, where shifting gears is never necessary.

Restrictions with Static Classes in C#

Our C# journey isn't without difficulties, though. For a smooth travel, we have to get around certain constraints.

An explanation of the problem "C# cannot declare instance members in a static class"

The unavailability of static classes to declare instance members is a significant drawback. Imagine this as a restaurant that serves only vegetarian food; it isn't allowed to sell you steaks because of its strict policies!

// This will lead to a compilation error in C#
public static class JaiminClass 
{
	public int cnt;  // Instance member!
}

We learned the new technique and evolved together.

Happy coding!!!


Similar Articles