In this article we will learn about one of the most reusable object oriented features of C#, static classes. We will learn about them from the basics because I have written this article focusing on students and beginners. Before proceeding further, please refer to my previous articles for a better understanding.
- Programming Methodologies
- Types of Classes in C#
- Polymorphism in C#
- Types of Inheritance in C#
- Method Overloading and Method overriding C#
- Sealed Class in C#
- Encapsulation in C#
- Interfaces in C#
What Static Classes Are
They are a type of class that cannot be initiated, in other words we cannot create an object of that class using the new keyword, such as class members can be called directly by using their class name.
The following are some key points:
- Created using the static keyword.
- Inside a static class only static members are allowed, in other words everything inside the static class must be static.
- We cannot create an object of a static class.
- A static class cannot be inherited.
- It allows only a static constructor to be declared.
- The methods of a static class can be called using the class name without creating an instance.
To demonstrate more about static classes, let us create a simple console application by creating the static class program, as in:
- Open Visual Studio from "Start" -> "All programs" -> "Microsoft Visual Studio".
- Then go to "File" -> "New" -> "Project..." then select "Visual C#" -> "Windows" -> "Console application".
- Then specify the name such as Partial class or whatever name you wish and the location of the project and click on the "OK" button. The new project is created.
- The Solution Explorer will look such as follows:
Now open the Program.cs file and write the following code
Now run the application and enter an input string as in the following:
Now press the Enter key and the output will be as follows:
Hence, from the preceding all examples it's clear that static class methods are directly accessed by the static class's name itself.
In the preceding article, I have briefly explained the use of a static class to make them understandable to beginners and newcomers. If you have any suggestion regarding this article then please contact me.