C# language supports static classes. In this article, we are going to learn when to use static classes in C# and how to implement them using a .NET (Core) console application.

To download the source code for this article, you can visit our GitHub repository.

Let’s begin.

What Are Static Classes?

Static classes are classes that cannot be instantiated by their users. All the members of static classes are static themselves. They can be accessed through the class name directly without having to instantiate them using the new keyword.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

Let’s take a look at a C# syntax when defining static classes:

static class ClassName  
{  
   //static methods  
   //static data members  
}  

Static classes contain static data members and methods. Besides that, these classes do not support inheritance and cannot have instance constructors like regular classes. Static classes can have one static parameterless constructor that cannot be inherited.

Let’s discuss how to implement static classes in C# using a simple Student class.Β 

How to Implement Static Classes in C#

A static class is defined using theΒ static keyword. Let’s define a static class calledΒ Student that stores students’ details such as names, date of birth, and ids:Β 

public static class Student
{
    private static string _name;
    public static int Id { get; set; }
    public static string Name { get { return _name; } set => _name = value; }
    public static DateTime DateOfBirth { get; set; }
}

Let’s go ahead and define a method CalculateAge to calculate the age of a student by using the DateOfBirth property:

public static int CalculateAge(DateTime DateOfBirth)
{
    var today = DateTime.Today;
    var age = today.Year - DateOfBirth.Year;
    if (DateOfBirth.Date > today.AddYears(-age))
    {
        age--;
    }
    return age;
}

After that, we can implement a static method called StudentDetails to return the properties of the Student class as a string:

public static string StudentDetails()
{
    var studentDetails = string.Empty;
    studentDetails = Name + " " + DateOfBirth + " " + CalculateAge(DateOfBirth);
    return studentDetails;
}

Next on, we shall proceed to invoke the static methods without instantiating the Student class in the Main method:

static void Main(string[] args)
{
    Student.Id = 1;
    Student.Name = "John Doe";
    Student.DateOfBirth = new DateTime(1994, 12, 31);
    Console.WriteLine("The student using a static class: " + Student.StudentDetails());
}

To understand the difference between static and non-static classes, let’s implement the same program through a non-static class.

That said, we are going to create a new CollegeStudent class that has the same properties and methods as the Student class:Β 

public class CollegeStudent
{
    private string _name;

    public int Id { get; set; }
    public string Name { get { return _name; } set => _name = value; }
    public DateTime DateOfBirth { get; set; }

    public int CalculateAge(DateTime DateOfBirth)
    {
        var today = DateTime.Today;

        var age = today.Year - DateOfBirth.Year;

        if (DateOfBirth.Date > today.AddYears(-age))
        {
            age--;
        }
        return age;
    }

    public string StudentDetails()
    {
        var studentDetails = string.Empty;
        studentDetails = Name + " " + DateOfBirth + " " + CalculateAge(DateOfBirth);
        return studentDetails;
    }
}

The next step is to modify our Main method to achieve the same result as the non-static class:

static void Main(string[] args)
{
    var student = new CollegeStudent();
    student.Id = 1;
    student.Name = "John Doe";
    student.DateOfBirth = new DateTime(1994, 12, 31);
    Console.WriteLine("The student details using a non-static class: " + student.StudentDetails());
}

As you can see in this case we had to instantiate theΒ CollegeStudent class.

Let’s discuss when and when not to use static classes.Β 

When Should We Use Static Classes?

Here are some of the scenarios where we might want to use static classes.

They are perfect for implementing utilities. Applications that don’t need any modifications or utility classes could use static classes. For example, in-built classes such as Math and System.Convert are some of the commonly used static classes.Β 

Static classes consume fewer resources. They do not require instantiation, hence, duplicate objects don’t take up additional memory space. Theoretically, static classes offer better performance than their non-static counterparts. This is usually unnoticeable in practical applications.

To use extension methods in our app, we have to use static classes.

When We Should Not Use Static Classes?

Of course, there are some cons to using static classes as well.

Static classes break the Object-Oriented Programming principle of polymorphism. It is difficult to change the functionality of a static class without modifying it. For example, creating child classes from non-static classes helps programmers extend existing functionalities without making changes to parent classes.Β 

Static classes cannot be defined through interfaces. They become infeasible when we need to reuse them when implementing interfaces.

As the functionality of a static method grows, it could result in the use of parameters that may not be needed. This is called parameter creep. The solution to this problem is to create derivative classes and overriding methods to support additional functionalities. However, as we have discussed in the previous points, static classes do not support inheritance and method overriding.Β 

Replacing the production code with the test code could be problematic during testing processes. We would need to use wrapper classes to test static classes.Β 

Differences Between Static and Non-static Classes

Here are some of the main differences between the static and non-static classes:

Static ClassesNon-static Classes
Do not support instantiationSupport instantiation through the newΒ keyword
Static classes do not support inheritanceThey allow inheritance
Can only have one private static parameterless constructor.
Cannot have instance constructors.
Can have non-static constructors
Static methods do not allow method overridingNon-static methods allow overridingΒ 

Let’s summarize what we’ve learned.

Conclusion

In summary, static classes can neither support instantiation nor inheritance. This makes them ideal for use in utility classes that do not need further modifications. On the other hand, if we need to add functionalities to our classes, non-static classes would be more ideal than their static counterparts.

 

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!