[C#] Static

I think every developer knows how static members of a class behave in your application. Static members are class-level fields and methods. They are not specific to each object.

In this article, I will explain static constructors and static classes. It is easy to understand how they work but there are some rules to follow.

 

1. Initializing Static Fields

When the default value of a static variable is known at compile time, you can just assign the value to a static field where the variable is declared.

public class Account
{
  public static double interestRate = 0.2;
}

 

2. Static Constructors

What if you do not know the value at compile time and the value should be retrieved at runtime? In the real banking applications, the interest rate usually retrieved from DB or a file.

To initialize the static members, C# provides static constructors.

  • Only a single static constructor can be defined. The static constructor cannot be overloaded
  • A static constructor does not take an access modifier
  • A static constructor does nor take any parameters
  • A static constructor executes exactly one time when the first instance of the class is created or when the first access to any static member is requested
  • The static constructor executes before any instance-level constructors
public class SavingsAccount
{
  public static double currInterestRate;

  static SavingsAccount()
  {
    // read the rate from DB
    currInterestRate = ...;
  }
}

 

3. Static Classes

You might create a class that only consists of static members. Utility classes can be an example. For this kind of class, it is meaningless to create an instance of the class. You can use some tricks to prevent the class from being instantiated; such as private constructors.

Designers of .NET knows this issue and allow you can apply the “static” keyword directly on the class level.

  • A static class can not be instantiated using the “new” keyword.
  • A static class may include only static fields and methods.
  • A static class is implicitly sealed. You can derive a class from a static class.
public static class SimpleCalculator
{
  public static int Add(int a, int b) { return a + b; }
  public static int Multiply(int a, int b) { return a * b; }

  public static void Test()
  {
    Console.WriteLine("1 + 2 = {0}", SimpleCalculator.Add(1, 2));
    Console.WriteLine("1 * 2 = {0}", SimpleCalculator.Multiply(1, 2));

    // SimpleCalculator cal = new SimpleCalculator(); // Error
  }
}

 

// Error:
// cannot be derived from static class
public class ComplexCalculator : SimpleCalculator
{
}

 

4. static readonly vs. const

A static readonly field and a const field work very similarly. The main difference between two is how you can initialize them.

  • At runtime using the static constructor : static readonly
  • At compile time: both static readonly and const

So if you know the value at compile time use a const field. If you need to set the value at runtime, use a static readonly.

public class SavingsAccount
{
  public const double primeInterestRate = 2.3;
  public static readonly double specialInterestRate;
  static SavingsAccount()
  {
    currInterestRate = ...; //from DB or a file
  }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s