All About Static Class In C#

In this article, I will demonstrate you all about static class with example. I will also let you know why we use the static class in place of normal class.

What is Static Class?

Static Class is a special type of class that is used to access the member functions without creating the object of the class. We can access static class members using the name of the class. The static keyword is used to create a static class. If you create a static class, all its members would be static.

Why to use static class?

If there is a requirement that we don’t need to create the instance of the class but we want to access their class members, then we create class as static.

Features of Static Class

  1. Static class contains only static members.
  2. You cannot create the instance of the static class.
  3. Static class can’t be inherited.

Example of Static Class

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Runtime.InteropServices;  
  6. using System.Globalization;  
  7.   
  8. namespace ConsoleApplication2  
  9. {  
  10.     public static class Square  
  11.     {  
  12.         public static double side;  
  13.   
  14.         public static double Perameter()  
  15.         {  
  16.             return side * 4;  
  17.         }  
  18.   
  19.         public static double Area()  
  20.         {  
  21.             return side * side;  
  22.         }  
  23.     }  
  24.   
  25.     public class Math  
  26.     {  
  27.         public static void Main()  
  28.         {  
  29.             Square.side = 20.02;  
  30.             Console.WriteLine("The side of square is " + Square.side);  
  31.             Console.WriteLine("The perameter of square is " + Square.Perameter());  
  32.             Console.WriteLine("The area of square is " + Square.Area());  
  33.             Console.ReadLine();  
  34.         }  
  35.     }  
  36. }  
Output

Output

Thanks for reading this article. Hope you enjoyed it.

 

Up Next
    Ebook Download
    View all
    Learn
    View all