Introduction
If we normally define static class; it is a class that cannot be instantiated. In other words, you can say class whose object cannot be created or a class where a new keyword cannot be used to create a variable of the class. The members of static class can be accessed by using the class name itself. We don’t need to make an instance of the class. A static class can only contain static members. Static classes are automatically loaded by .NET Framework CLR.
Declaration
A static class can be created, using the keyword “Static”.
e.g.
In the code given above, class with name MyClass is static as Static keyword is used before class.
Features of static class
- Static class contains only static members.
- It cannot be instantiated.
- Static class is always sealed.
Understanding Static Class
Methods in static class are accessed, using the class name.
e.g.
- static class MyClass
- {
- public static void MyFunc()
- {
- Console.WriteLine("Method from static class");
- }
- }
-
-
-
- static void Main(string[] args)
- {
- MyClass.MyFunc();
- Console.ReadLine();
- }
Creating an Instance of Static class
As I already said Static class cannot be instantiated, let us see this in an example by trying to create the instance of Static class.
- class Program
- {
- static void Main(string[] args)
- {
- MyClass mc = new MyClass();
-
-
-
- }
- }
-
- static class MyClass
- {
- public static void MyFunc()
- {
- Console.WriteLine("Method from static class");
- }
- }
While ignoring the warning and trying to run the program, we get this error.
Now, we will create a static class with one sum function and will call the sum function, using class name.
MySumFunc function has two input parameters for the sum. We will provide two input parameters to the function , while calling it to check the output.
- class Program
- {
- static void Main(string[] args)
- {
- int result;
- result = MyClass.MySumFunc(3, 4);
- Console.WriteLine(result);
- Console.ReadLine();
- }
- }
-
- static class MyClass
- {
- public static int MySumFunc(int a, int b)
- {
- return a + b;
- }
- }
After running the program , we will get the desired result, 7 (as we are providing 3 and 4 to sumFunc).