Static Constructors
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:
public class StaticConstructorTestClass{private static readonly string someStaticString = string.Empty;static StaticConstructor(){someStaticString = GetFromDatabaseOrWhatever();}private static string GetFromDatabaseOrWhatever(){// Do the processing herereturn "This is a string I got from database";}}
The Rules:
When creating static constructors, keep these rules in mind:
Only one static constructor per class.The constructor canât have any parameters.The constructor canât have an access modifier (public/private/etc).The constructor executes before any instance constructor.The constructor executes only one time per class.