Hello readers, In this tutorial, I am going to cover a very important topic “static class” in C#. A static class is a class that is declared using the static keyword and cannot be instantiated. Let’s discuss static class in detail.

What is a static class in C#?

Like any other programming languages C, C++, and Java, C# also introduces the concept of static class. A static class is a class that is declared using the static keyword.
A static class can not be instantiated that means we cannot use the new keyword to create the object of the static class. A static class must contain only static member. The main advantage of using a static class that it guarantees that the instance of the class cannot be created. Since we cannot create an instance of a static class and a static class can only have a static member so to access the member of static class we use class name itself. For example, if I have a class called MyStaticClass that has a public method called MyStaticMethod then to access the member of a static class you need to write the following line of code.

MyStaticClass.MyStaticMethod();

Why we need a static class:

A static class does not allow a user to create an instance of the class as well as it restricts the user to inherit the class. So static class make your implementation simpler, safe and faster because you do need to have to create an object in order to access the member of the class.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;
namespace StaticClassDemo
{
 class Program
 {
 public static class MyStaticClass
 {
 public static int myStaticVariable = 0;

public static void MyStaticMethod()
 {
 Console.WriteLine("This is a static method.");
 }

public static int MyStaticProperty { get; set; }
 }


 static void Main(string[] args)
 {

Console.WriteLine(MyStaticClass.myStaticVariable);
 MyStaticClass.MyStaticMethod();
 MyStaticClass.MyStaticProperty = 100;
 Console.WriteLine(MyStaticClass.MyStaticProperty);
 Console.ReadLine();
 
 }
 
 }
}

Output:

0
This is a static method.
100

 

Point of interest for static class:

  • you cannot create an instance of a static class.
  • A static class must contain only static members.
  • A static class is implicitly sealed class and therefore a static class cannot be inherited.
  • A static class cannot have instance constructor because we cannot instantiate a static class.
  • Access modifiers are not allowed for a static class.
  • To access the member of static class we use class name {.} method name.

View More:

Conclusion:

I hope you would love this post. Please don’t hesitate to comment for any technical help. Your feedback and suggestions are always appreciated.

Thank You.

Leave a Comment