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.
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:
- We can't create any objects of it.
- We can't even create subclasses of it (it is sealed).
- It must contain only static members.
- 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);
}
}
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);
}
}
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();
}
}