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 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.
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 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 one private static parameterless constructor. Cannot have instance constructors. | Can have non-static constructors |
Static methods do not allow method overriding | Non-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.
thanks
A static class is not a class that can not be instatianted. A static class is a class that can have one instance only through the entire lifecycle of the app. Major difference in these concepts.
To make sure static classes have a single instance, microsoft designed them to support a parameterless static constructor which is also private, therefore, the static classes can not be instantiated by code; they are instantiated automatically by the framework.
To summerize using causality:
The cause of a static class is to have a sinlge instance, therefore, the effect is it can not be instantiated by code; it is instantiated automatically by runtime
That makes sense and it’s true. What we meant is that static classes cannot be instantiated by a user.
Thank you for your input, we’ll clarify that in the text.
Why does this claim static classes cannot have a constructor? They definitely can, a static constructor..
Hey Joe, that’s right. We should have made it clear that we’re talking about instance constructors, not the static ones. Static classes can indeed have one static constructor. We’ve made some changes to make it more clear.
Another advantage is that it is single instance and you can use the same instance through the entire application, for example a DB accessor that you want to lock is methods.
** of course it’s better to use DI mechanism for this things.
In this db-example, a singleton-class would be preferred over a static class.
A big downside of static classes is that you cannot mock them for testing.
Static classes are usually used for defining extensions on other classes and holding static values like string-constants that are not user-oriented (those should be in the resources where it is easier to provide translations).