a blog for those who code

Monday 11 August 2014

C# Static Classes

In this post we will show you what are Static Classes in C# and what is the use of it. Static Classes are the classes which cannot be instantiated and it must contain only static members.

For Example, if you look into System.Console class which is a Static Class, all the members of that class are static. This class is not intented to be instantiated but you can access all the members of that class using the class name. Console.WriteLine();


So, you might ask that then what's the use of Static Class? As per MSDN
A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not get or set any internal instance fields. 
That means you will make those classes as static class which contains some methods to do some task, without any requirement of storing or retrieving data. If we look into Console Class, you are not required to store any value or get any value out of it. It has some predefined functions which you need to use.

Program shows the usage of Static class:
using System;
class Program
{
   static void Main()
   {
       Class1 cl = new Class1() // Error
       Class1.Method1() // Works fine
   }
}
class Class1
{
   static void Method1()
   {
       Console.WriteLine("I am inside Method1");
   }
}

One think to know that you can create Static Classes but not Static Structures, because CLR always allows value types to be instantiated, there is no way prevent that.

Restrictions on Use of Static Classes :
1. You can not define any instance members inside static class, you have to define only static members.
2. You cannot implement any interfaces in static classes, because you can only call interface methods when you are creating an instance of a class.
3. They cannot inherit from any class except System.Object.

Please Like and Share the Blog, if you find it interesting and helpful.

1 comment:

  1. I think the most common place I run into actually creating static classes is when writing extension methods. They're required to be in a static class.

    ReplyDelete