Static Classes for Utilities
Group helper functions in static classes.
What Is a Static Class?
A static class is declared with static class. It can contain only static members and cannot be instantiated. It is the natural home for utility functions.
using System;
static class StringUtils
{
public static string Shout(string s) => s.ToUpper() + "!";
}
class Program
{
static void Main()
{
Console.WriteLine(StringUtils.Shout("hello"));
}
}Cannot Create Instances
You never write new for a static class. All access goes through the class name directly.
using System;
static class MathUtils
{
public static int Cube(int x) => x * x * x;
}
class Program
{
static void Main()
{
// No instance needed
Console.WriteLine(MathUtils.Cube(3));
}
}All lessons in this course
- Static Methods and Fields
- Static Classes for Utilities
- Constants and readonly Fields
- Static vs Instance Design