In c#, a static class can be created by using static
modifier and the static class can contain only static members.
Generally, the static class is same as the non-static class, but the only difference is the static class cannot be instantiated. Suppose if we apply static
modifier to a class, we don't require to use the new keyword to create a class type variable.
Another difference is the static class will contain only static members, but the non-static class can contain both static and non-static members.
In c#, we can create a static class by applying static
keyword to the class like as shown below.
If you observe the above syntax, we applied static
keyword to the class type to create a static class called “sample”. The methods and data members that we are going to implement in the sample class must be static.
In c#, we can access members of a static class directly with the class name. For example, we have a static class called “User” with a method “Details()” that we can access like User.Details().
Following is the example of defining a static class to access data members and member functions without creating an instance of the class in the c# programming language.
If you observe the above example, we are accessing static class members and functions directly with the class name because we cannot instantiate the static class.
When you execute the above c# program, you will get the result below.
This is how we can create a static class and use it in our c# applications based on our requirements.
Following are the main features of static class in c# programming language.
As discussed in the static keyword article, we can use static members in non-static classes such as normal classes. For normal classes, you can create an instance of a class using the new keyword to access non-static members and functions, but it cannot access the static members and functions.
To know more about it, refer to the static keyword in c# with examples.
The advantage of using static classes in c# applications will make sure that instances of classes cannot be created.