A static class is the same as a non-static class, the only difference is that a static class cannot be instantiated.
Similar to static members, a class is static when the keyword static is used in its declaration.
[<AccessModifier>] static class <ClassName>
{
// … Class body goes here
}
Let's suppose that we have a class with a single method that always works in the same manner. For example, we have a method that takes two numbers as a parameter and returns their sum as a result.
Let's have a look into the following static class which contains three static methods.
public static class MathUtility
{
public static int Add(int number1, int number2)
{
return (number1 + number2);
}
public static int Subtract(int number1, int number2)
{
return (number1 - number2);
}
public static int Multiply(int number1, int number2)
{
return (number1 * number2);
}
}
You can call static members using the class name.
int number1 = 5;
int number2 = 9;
int result1 = MathUtility.Add(number1, number2);
int result2 = MathUtility.Subtract(number1, number2);
int result3 = MathUtility.Multiply(number1, number2);
Console.WriteLine("{0} + {1} = {2}", number1, number2, result1);
Console.WriteLine("{0} - {1} = {2}", number1, number2, result2);
Console.WriteLine("{0} * {1} = {2}", number1, number2, result3);
Let's run the above code and you will see the following output.
5 + 9 = 14
5 - 9 = -4
5 * 9 = 45
All the examples related to the static class are available in the StaticClass.cs
file of the source code. Download the source code and try out all the examples for better understanding.