C# Static Classes: Methods & Usage

Static classes in C# are similar to regular classes in how they are used, but there are a few key differences:

  1. Static classes cannot be instantiated, so their member methods must be static.
  2. The member methods of a static class can be called directly using the class name, without the need for an instance object.
  3. Static classes are typically used to contain a set of related static methods and are not suitable for storing data specific to instances.

Here is an example of a static class:

public static class MathUtils
{
    public static int Add(int a, int b)
    {
        return a + b;
    }

    public static int Subtract(int a, int b)
    {
        return a - b;
    }
}

class Program
{
    static void Main()
    {
        int sum = MathUtils.Add(5, 3);
        int difference = MathUtils.Subtract(5, 3);

        Console.WriteLine($"Sum: {sum}");
        Console.WriteLine($"Difference: {difference}");
    }
}

In the example above, MathUtils is a static class that includes two static methods, Add and Subtract. These methods can be accessed directly by using the class name MathUtils.

bannerAds