C# Static Class
In C#, a static class is a class that cannot be instantiated, and it can only contain static members (fields, methods, properties). This guide covers the syntax, usage, and characteristics of static classes in C#.
Syntax
public static class MyStaticClass
{
public static int myStaticField;
public static void MyStaticMethod()
{
// Static method implementation
}
}
Example
public static class Logger
{
public static void Log(string message)
{
Console.WriteLine($"[LOG] {message}");
}
}
class Program
{
static void Main()
{
Logger.Log("Application started.");
}
}
Output
The output will be a log message indicating that the application has started.
Explanation
- A static class is declared using the
static
keyword before theclass
keyword. - All members of a static class must be static.
- In the example, the
Logger
static class contains a static methodLog
for logging messages.
Use
Use a static class in C# when:
- You want to group related static members together.
- Instantiating objects of the class is not required.
- You need a centralized location for utility methods or constants.
Important Points
- Static classes cannot be instantiated with the
new
keyword. - All members of a static class must be static.
- Static classes are often used for utility purposes, such as logging, helper methods, or constants.
Summary
C# static classes provide a way to organize and encapsulate static members in a coherent and centralized manner. They are often employed for utility functions, constants, or methods that don't require instance-specific data. Understanding the characteristics and use cases of static classes can contribute to writing more modular and efficient C# code.