Summary: in this tutorial, you’ll learn about the C# static classes and how to use them to define utility classes.
Introduction to C# static classes
A static class is a class that cannot be instantiated. Typically, you use a static class to group members that are specific to a class, not an instance of the class.
A common use of a static class is to create a utility class that contains a set of methods and values like the Math library.
A static class has the following characteristics:
- A static class declaration needs to have the
static
keyword. - A static class has only static members including static fields, properties, and methods.
- A static class cannot have any instance constructor but can have a static constructor.
- A static class is implicitly sealed. Therefore, you cannot subclass it.
To access members of a static class, you use the class name and the member name.
C# static class example
Let’s see an example of using a static class to define a utility class.
First, define a static class LengthConverter
:
static class LengthConverter
{
public static double FeetToMeters(double ft) => ft / 3.28084;
public static double MetersToFeet(double m) => m * 3.28084;
}
Code language: C# (cs)
The LengthConverter
static class has two static methods that convert feet to meters and vice versa.
Second, use the LengthConverter
class:
// Program.cs
double feet, meters;
// feet to meters
feet = 100;
meters = LengthConverter.FeetToMeters(feet);
Console.WriteLine($"{feet}ft = {meters:0.##}m");
// meters to feet
meters = 10;
feet = LengthConverter.MetersToFeet(meters);
Console.WriteLine($"{meters}m = {feet:0.##}ft");
Code language: C# (cs)
Output:
100ft = 30.48m
10m = 32.81ft
Code language: plaintext (plaintext)
Starting from C# 6, you can access members of a static class without the class if you have a using static
directive. For example:
// Program.cs
using static LengthConverter;
double feet, meters;
// feet to meters
feet = 100;
meters = FeetToMeters(feet);
Console.WriteLine($"{feet}ft = {meters:0.##}m");
// meters to feet
meters = 10;
feet = MetersToFeet(meters);
Console.WriteLine($"{meters}m = {feet:0.##}ft");
Code language: C# (cs)
Summary
- A static class cannot be instantiated and subclassed.
- A static class only has static members.
- Use a static class to define a utility class.