Example 1
private const string _DefaultIconPath = _IconsPath + "default.ico";
private const string _IconsPath = "Icons/";
Value of these strings at runtime:
- _DefaultIconPath: "Icons/default.ico"
- _IconsPath: "Icons/"
Example 2
private readonly string _DefaultIconPath = _IconsPath + "default.ico";
private readonly string _IconsPath = "Icons/";
Compile time error:
A field initializer cannot reference the non-static field, method, or property '_IconsPath'
Example 3
private static readonly string _DefaultIconPath = _IconsPath + "default.ico";
private static readonly string _IconsPath = "Icons/";
Value of these strings at runtime:
- _DefaultIconPath: "default.ico" (_IconsPath evaluated to
null
) - _IconsPath: "Icons/"
Question
Why doesn't the compiler throw a compilation error in example 3 similar to example 2?
The order of the declaration matters in the case of static readonly
field definitions, but not in the case of const
field definitions.
Edit:
I understand why the strings are initialized to those specific values. What I don't understand is why Example 2 throws a compilation error, forcing initialization to occur in a constructor rather than in the declaration of the variables (which makes perfect sense), but Example 3 doesn't behave in the same manner. Wouldn't it make sense to throw the same compilation error forcing the initialization to occur in a static constructor?
Another Example
private static string test = test2;
private static string test2 = test;
This example demonstrates what I'm trying to explain. The compiler could force initialization of static state in a static constructor (as is does for instance variables). Why does the compiler allow it (or why does the compiler disallow this for instance variables)?