Close
Close

C# Static Class


Suppose you have made a class Rectangle which has two static methods - GetArea(int length, int breadth) and GetPerimeter(int length, int breadth) to get the area and perimeter of a rectangle by passing the length and the breadth to them. In this case, we have no need to create objects of the Rectangle class and we can directly use these static methods on the Rectangle class.

static class in C#

In these kinds of cases, we can even prevent our class from creating any objects by using a static class. A static class is like a normal class but:

  1. We can't create any objects of it.
  2. We can't even create subclasses of it (it is sealed).
  3. It must contain only static members.
  4. It can't contain instance constructors.

We use static keyword to define a static class. Let's take an example.

using System;

static class Circle
{
public static double pi = 3.14;

public static void PrintArea(double radius)
{
  Console.WriteLine($"Area is {pi*radius*radius}");
}

public static void PrintCircumference(double radius)
{
  Console.WriteLine($"Circumference is {2*pi*radius}");
}
}

class Test
{
static void Main(string[] args)
{
  Circle.PrintArea(2);
  Circle.PrintCircumference(2);
}
}
Output
Area is 12.56
Circumference is 12.56

We can have a static constructor inside a static class. Let's take an example.

using System;

static class Circle
{
public static double pi;

static Circle()
{
  pi = 3.14;
}

public static void PrintArea(double radius)
{
  Console.WriteLine($"Area is {pi*radius*radius}");
}

public static void PrintCircumference(double radius)
{
  Console.WriteLine($"Circumference is {2*pi*radius}");
}
}

class Test
{
static void Main(string[] args)
{
  Circle.PrintArea(2);
  Circle.PrintCircumference(2);
}
}
Output
Area is 12.56
Circumference is 12.56

Let's try creating an object of a static class and see the error.

using System;

static class Circle
{
public static double pi;

static Circle()
{
  pi = 3.14;
}

public static void PrintArea(double radius)
{
  Console.WriteLine($"Area is {pi*radius*radius}");
}

public static void PrintCircumference(double radius)
{
  Console.WriteLine($"Circumference is {2*pi*radius}");
}
}

class Test
{
static void Main(string[] args)
{
  Circle c = new Circle();
}
}
Output
hello.cs(27,5): error CS0723: 'c': cannot declare variables of static types
hello.cs(3,14): (Location of the symbol related to previous error)
hello.cs(27,16): error CS0712: Cannot create an instance of the static class 'Circle'

Ask Yours
Post Yours
Doubt? Ask question