C#: Static classes

A static class is quite similar to non static class except that a static class has no instance variable.

Or in another words, there are no variable needed to be declared inside a static class.

When you are designing a class and you find that variables are not needed inside a class, you can consider to assign the class as static.

It can be used as a convenient container for methods that just operate on input parameters

As there is no instance variable, you could not use new keyword to create a variable of the class.

Consider the following example:
using System;

namespace Math
    public static class Calculate
        public static int Add(int a, int b)
            return a + b;
        static void Main()
            int x;

            x = Calculate.Add(10, 15);


Class Calculate is static as I do not need variables for the class Calculate to function.  Take note also that the Add member function of the class is also static.

A static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.

And so when I access the Add member, I can access it by directly using class Calculate as in:

Calculate.Add(10, 15);

This Add method is a mathematical function.  We can add a few other related mathematical functions such as multiply, sum etc and make them all to be static members.

You just have to ensure that they can operate on only input parameters similar to the Add method.



Series Navigation<< C#: Static variables
C#: Variable scope >>