What is C# Static class? Explain with example and USE

Answer includes C# static class with concept and example program. also, Static classes uses with important points will be described.

In simple word, when we want to keep only static methods and static variables in the class then we create a static class. There should not be any non-static member field in the class.

How to create static class?
To create a static class, a class declaration should be preceded by static keyword. That’s it.

c# code example

 

Since, we don’t have any instance method or instance field in the class, hence, we don’t need to create any object of this class. that’s why object creation of a static class has been blocked at compiler level itself. So, we cannot create an object of a static class in C# program.

Also, since, we cannot create an object of this class and cannot have instance method or field, there is no point of having static class constructor in C# programming. also, as we know that constructor is used to initialize instance filed. But, it should be noted that static constructor in a static class can be written.

Note that a static class cannot be inherited as it is by default sealed in C# language. You can read about sealed class and method in C# object oriented programming.

Generally, static classes are used to create a helper or a utility classes where an object (instance fields) are not required. For example, we may want to write some error logging class or any kind of utility class where methods can be called using class name only and object is not required.

Important points about C# Static Classes
  • We cannot create an instance of a static class. e.g. MyClass obj = new MyClass;
  • Static class cannot be inherited.
  • Static class cannot have an instance constructor, but, can have static constructor.