The Problem

Suppose you have a static readonly string whose value you don’t know until runtime. Maybe you have to read it from FileAbcdefgh.txt when certain condition is true and read it from FileXyz.txt when it’s not. But once set, the value should never be modified again.

The Solution

I’m assuming you guessed that the solution to the problem is static constructors. You guessed right. ;) Static constructors, like the null coalescing operator, are a C# feature I was not aware of until fairly recently.

Static constructors look fairly similar to normal (default) constructors:

  1. public class StaticConstructorTestClass
  2. {
  3. private static readonly string someStaticString = string.Empty;
  4.  
  5. static StaticConstructor()
  6. {
  7. someStaticString = GetFromDatabaseOrWhatever();
  8. }
  9.  
  10. private static string GetFromDatabaseOrWhatever()
  11. {
  12. // Do the processing here
  13.  
  14. return "This is a string I got from database";
  15. }
  16. }

The Rules:

When creating static constructors, keep these rules in mind:

  1. Only one static constructor per class.
  2. The constructor can’t have any parameters.
  3. The constructor can’t have an access modifier (public/private/etc).
  4. The constructor executes before any instance constructor.
  5. The constructor executes only one time per class.