Home > DeveloperSection > Blogs > Static class

Static class


C# C# 
Ratings:
0 Comment(s)
 1166  View(s)
Rate this:

Static class


In this blog, I’m explaining the concept of static class.

Static class is basically like a non-static class but it can never be instantiated. In other word you cannot use the new keyword to create an object of a class. Because there is no instance variable, you access the members of a static class by using the class name itself. For example, in the built in System.Math staic class and their function direct access by the name.

There are following features of static class:

·         Contains only static members: static class same as but contains only static members and private constructor.

·         Cannot be instantiated: a private constructor to prevent to create an instance.

·         Is sealed: static classes are sealed because it cannot be inherited.

·         Cannot contain instance Constructor: Static classes cannot contain an instance constructor; however, they can contain a static constructor. Non-static classes should also define a static constructor if the class contains static members that require non-trivial initialization.

Example 1

public static class staticClass

    {

    }

  

    class Program

    {

        static void Main(string[] args)

        {

            staticClass obj = new staticClass(); // cannot create static class instance

        }

    }

In this example, give the error cannot declare a variable of static type and cannot create a instance of static class.

This is the screen shot of the static class instantiation error.

Example 2

static class Rectangle

    {

      //All static member variables

        static int width = 4;   //width of rectangle

        static int height = 5;   //height of rectangle

 

      //Member functions

       public static int rectangleArea()

        {

           return width*height;

        }

    } //class end

  

    class Test

    {

        static void Main(string[] args)

        {

           

            //<ClassName>.<MethodName>

            Console.WriteLine("Rectangle area is: "+Rectangle.rectangleArea());

            Console.ReadKey();

          

        }

    }

Output is: Rectangle area is: 20

In this example, calculate the area of rectangle by static class.


Don't want to miss updates? Please click the below button!

Follow MindStick