A static class is a class that cannot be instantiated and can only contain static members such as methods, properties, fields, and events. These members are accessible through the class name rather than an instance of the class.
Here are some common use cases for static classes:
Utility Classes:
A static class can be used to create a utility class that contains a set of related methods that perform common tasks. For example, the Math class in the .NET Framework is a static class that contains a set of mathematical functions.
Extension Methods:
A static class can also be used to define extension methods that add functionality to an existing class without modifying the class itself. Extension methods must be defined in a static class.
Constants:
A static class can be used to define a set of constant values that are used throughout an application. This makes it easy to change the value of a constant in one place and have the change propagate throughout the application.
Singleton Pattern:
A static class can be used to implement the Singleton pattern, which ensures that only one instance of a class is created and provides a global point of access to that instance.
Performance:
Static methods are faster than instance methods because they don't have to create an instance of the class before invoking the method. This can be useful in performance-critical scenarios.
Here's an example of a static class:
public static class UtilityClass
{
public static int Add(int a, int b)
{
return a + b;
}
public static string ReverseString(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
}
In the above example, UtilityClass is a static class that contains two static methods: Add() and ReverseString(). These methods can be called directly on the class name without creating an instance of the class.
In summary, a static class in C# is a class that cannot be instantiated and contains only static members. It can be used to create utility classes, define extension methods, define constants, implement the Singleton pattern, and improve performance.