CSharp - Add static method to static class

Introduction

We can create static variables or static methods.

In C#, the class itself can be static.

When we tag the keyword static to a class, it is a static class.

When static is tagged with a method, it is called a static method.

When we associate static with a variable, it is known as a static variable.

Demo

using System;


static class Rectangle
{
    public static double Area(double len, double bre)
    {/*from ww w.j  a va  2 s.c  om*/
        return len * bre;
    }
}
class Program
{
    static void Main(string[] args)
    {
        double length = 25;
        double breadth = 10;
        Console.WriteLine("Area of Rectangle={0} sq. unit", Rectangle.Area(length, breadth));
    }
}

Result

Analysis

We have invoked the Area() method of the Rectangle class through the class name.

We did not make any instance of the Rectangle class here.

static classes are sealed and they cannot be inherited or instantiated.

static classes can contain only static members.

A static class cannot contain instance constructors.

system.Console and system.Math are common examples of static classes.

Related Topic