Site icon

Static Class in C#

Static class in C# is a special class that cannot be instantiated . In other words , you cannot create an object of a static class and cannot access static members using an object. You can access the public static members (methods, fields and properties) using dot operator (ClassName.MemberName).

In .Net framework, we have certain static classes such as Console, Math, Environment and ThreadPool, these classes have only static methods and the sole purpose of these classes is to group some related members and functionality together. Lets look at below Math class .

If you look at above Math class, then you can find all static methods in it, these methods can be accessed by using dot(.) operator (ClassName.MemberName) as follows.

Key Properties of Static Classes :

Create a Static Class in C# ?

You can create a static class by adding static modifier before the class name and after the access modifier as follows.

Static class and static method example:

In below example,

When we run above example, then below out put generated.

Here, in above we invoked static methods static int CalculateMax(int[] arrNum) and static int CalculateMin(int[] arrNum)  method by using dot (.) operator as follows.

How C# compiler handles it ?

C# compiler marks the class as Abstract and Sealed. If you look at the below IL (Intermediate Language) code of above sample, generated through ILDASM (IL Disassembler) tool , then you can notice that the C# compiler has converted the class MathsCalculator to a Abstract and Sealed class as .class public abstract auto ansi sealed beforefieldinit StaticClassDemo.MathsCalculator .

The purpose of having Abstract and Sealed modifier is as follows :

Important points about static class in C# :

Following are some of the key points.

Thanks for your time 🙂 keep visit my other articles and also check out my article on Partial Class in C#

Exit mobile version