Static Class in C# why and when with examples

C# Static Method, Class and Constructor Static Classes and Static Class Members c# - Why and when should I make a class 'static'? Static class in C# When we need static class best example of static class constructor of static class static and non static constructor static and non static method overriding

Static class, static method and static constructor are some common questions which are asked in most interviews. A static class is basically the same as a non-static class, but there in one difference, a static class cannot be instantiated, means we cannot use new keyword to create an object of the class. Even we cannot create any parameterized constructor because to pass the constructor value we need to create object, we will check all these points in more detail in this article.

When we can use static class?

We have a class Math in C#, let’s check it’s methods and operation. Say Math.Min, it takes two values of different data types and return minimum one, similarly Max, Round, Floor, Ceiling. If you notice all these methods take some values and operate only those provided values. So a static class should be container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields.

What is a static class?

A static class is similar to normal class with these differences

  1. Contains only static members means all the methods and members must be static
  2. Cannot be instantiated by using new keyword
  3. By default it is sealed class and therefore cannot be inherited.
  4. It can have default constructor or
  5. Can have only one constructor without any parameter
  6. Access modifiers are not allowed on static constructors
  7. Cannot have instantiate constructors
  8. Methods can be called by using class name dot (.) method name.

What is a static Method?

Static method are similar to regular (instantiate) method, but they can be accessed directly by using the class name rather than the instance of the class, it will give error if we will try to access them with class instance, see it with this example:

public class Sample
{
    public void DisplayInst()
    {
        Console.WriteLine("I am a instance method");
    }

    public void DisplayStatic()
    {
        Console.WriteLine("I am a static method");
    }
}

Call these two methods with instance and directly, see this

var obj = new Sample();
obj.DisplayInst();  // I am a instance method
obj.DisplayStatic(); // Wrong, it cannot be called

// Let’s try to call them directly
Sample.DisplayInst();  // Wrong, it cannot be called
Sample.DisplayStatic(); // I am a static method

Can we have static as well as instantiate constructor in a class?

  1. Yes, it can be in a normal instantiate class
  2. Any number of instantiate constructors
  3. With zero to any number of parameters
  4. Can have only one static constructors
  5. Static constructor cannot have any parameter
  6. Static constructor are mostly used to initialize some values

We will create a simple Car class with different constructors and a static constructor to understand the feature, let’s create a class with two instantiate constructor, one static constructor and two Detail methods

public class Car
{        
    String _color = "White";

    static decimal _price = 25000;
    static Decimal _discount = 100;

    public Car()
    {
    }

    public Car(String color)
    {
        this._color = color;
        _discount = 500;
    }

    static Car()
    {
        _discount = 1000;
    }

    public String Detail()
    {
        return String.Format("Price: {0:C} and Color: {1} "
                                , _price - _discount, _color);
    }

    public static String Detail(String color)
    {
        return String.Format("Price: {0:C} and Color: {1} "
                                , _price - _discount, color);

    }
}

It is valid and working class which has both types of constructors and methods, if you can see there is a normal constructor without any parameter and one static constructor without any parameter, because static constructor cannot have any parameter. Let's try to execute them one by one

  1. var car = new Car(); car.Detail();

    • Output: Price: $25,000 and Color: White
  2. var car = new Car(“Black”); car.Detail();

    • Output: Price: $24,500 and Color: Black
    • One parameter constructor is called and assign the discount $500
  3. Car.Detail(“Red”);

    • Output: Price: $24,000 and Color: Red
    • When we will call Detail method, constructor will be called before executing the method.

Try to add a new constructor like this and you will get following error

public static Car(Int32 color)
{
}
  1. a static constructor must be parameterless
  2. access modifiers are not allowed on static constructors

Conclusion:

  1. Easy to use
  2. No need to create instance before calling the methods
  3. Cannot have more than one constructor
  4. Constructor cannot have any parameter
  5. Access modifier cannot be use with constructor
  6. Constructor is called before calling any method internally
  7. Cannot be instantiated
  8. Cannot be inherited because by default it is sealed
Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • oops
  • c#
By Ali Adravi On 01 Jan, 15  Viewed: 23,726

Other blogs you may like

IEnumerable and IEnumerator in C# with real time example

We will discuss here what is IEnumerable, IEnumerator, what are differences between them, where should we use IEnumerable and where to IEnumerator, once we will finish our discussion it will be clear, which one would be best for which situation and why, so let’s see it with example To better... By Ali Adravi   On 29 Mar 2013  Viewed: 44,580

Interface in C# with real time example

In this article we will discuss about interface in C# with real time example, it properties, implementations and pros and cons as well. 1. An interface can never be instantiated e.g. ICar car = new ICar(); It’s wrong. 2. It only contains signature of its methods. 3. An interface has neither... By Ali Adravi   On 18 Aug 2013  Viewed: 47,535

Method overloading in C# with example

Method overloading means having different methods with same name but with different types of parameters or number of parameters also known as static polymorphism. In this article we will try to understand what is method overloading and how we can overload a method with example. Suppose we have a... By Hamden   On 19 Jul 2013  Viewed: 3,124

Polymorphism in C# with example

Polymorphism is derived from two Latin words, 1. Poly means many 2. Marphose means forms. By using inheritance, a class can be used as many types, say we have a Person which may be a Professor, may be a Student, may be Clerk. So in this article we will see some example of Polymorphism. When we... By Hamden   On 01 Jun 2013  Viewed: 4,548

Convert string to an enum type in .net

Sometime we need to convert string to an enum type, say I need to store my enum value into viewstate then we cannot store enum or any object to viewstate so converted that to string and store it, and on postback need to read the viewstate and convert to enum, so how to convert a string into enum?... By Hamden   On 21 May 2013  Viewed: 1,542