This is because the static constructor is called automatically before the first instance is created or any static members are referenced..
This means that when an instance of otherClass
invokes IDs.someID = sym;
the first operation that gets executed is the static constructor, i.e. the code inside static IDs()
.
At this point the static variable has not yet been initialized, and you are basically executing log.info(null);
.
After the static constructor completes, the variable is initialized, so you should be able to see its value inside otherMethod
, after the first reference of IDs
.
Given the OP's requirement:
I want to use the value passed in someID
in a switch statement
The solution could be to simply execute a static method whenever a new value is set, with the help of explicit getters and setters:
public static class IDs
{
private static string _someID; // backing field
public static string SomeID
{
get { return _someID; }
set
{
_someID = value;
DoSomethingWithSomeID();
}
}
private static DoSomethingWithSomeID()
{
// Use SomeID here.
switch (IDs.SomeID)
{
...
}
}
}
public class OtherClass
{
public void OtherMethod(string sym)
{
// This will set a new value to the property
// and invoke DoSomethingWithSomeID.
IDs.SomeID = sym;
}
}
DoSomethingWithSomeID
will be invoked every time someone sets a new value to SomeID
.