blog

Home / DeveloperSection / Blogs / Static class

Static class

Anchal Kesharwani2695 12-Aug-2014

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

publicstaticclassstaticClass
    {
    }
  
    classProgram
    {
        staticvoid Main(string[] args)
        {
            staticClass obj = newstaticClass(); // 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.

Static class

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

Example 2

staticclassRectangle
    {
      //All static member variables
        staticint width = 4;   //width of rectangle
        staticint height = 5;   //height of rectangle
 
      //Member functions
       publicstaticint rectangleArea()
        {
           return width*height;
        }
    } //class end
  
    classTest
    {
        staticvoid 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.


Updated 18-Sep-2014

Leave Comment

Comments

Liked By