Search code examples
c#.netoopc#-4.0constructor

What is the advantage of initializing static variable in a static constructor instead of direct assignment of value


In the below-mentioned code, there are two ways of assigning the value of the static variable 'RateOfInterest'.

  1. By directly assigning the value.
  2. By assigning in a static constructor.

I believe for multiple objects of the 'Customer' class, 'RateOfInterest' will have only one memory allocation using either approach. (Please correct me if I am wrong).

Is there any specific advantage of one approach over the other.

class Customer
{
    int AccNo;
    static int RateOfInterest;
    //static int RateOfInterest = 10;    // Approach 1
    static Customer()
    {
        RateOfInterest = 10;          // Approach 2
    }
    public Customer(int AccNo)
    {
        this.AccNo = AccNo;
    }
    public void Display()
    {
        Console.WriteLine($"AccNo : {AccNo}, Rate : {RateOfInterest}");
    }
}

Solution

  • they will be compiled in to same thing. so no difference,

    That's not private constructor. that's static constructor

    A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced

    I use static constructor when by directly assigning value, the line becomes too long (that's opinion based) or when I need multiple lines to initialize a value.