When to Use Static Classes in C#

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.

Let’s begin.

What Are Static Classes?

Static classes are classes that cannot be instantiated. 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.

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 constructors. 

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.

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.

Differences Between Static and Non-static Classes

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

Static Classes                                                         Non-static Classes
Do not support instantiation                                 Support instantiation through the new keyword
Static classes do not support inheritance         They allow inheritance
Can only have static constructors                         Can have non-static constructors
Static methods do not allow method overriding Non-static methods allow overriding 

Post a Comment

0 Comments