The following code throws a NRE exception trying to log the exception:
public static class FooClass
{
public static string Foo { get; } = CalculateFoo();
static CalculateFoo()
{
try
{
DoSomethingThatFails();
}
catch (Exception ex)
{
_log.Debug(ex); // ----> _log is null here <----
}
}
static readonly ILog _log = LogManager.GetLogger("FooClass");
}
The reason _log
is null, is because the compiler first initialize Foo
property, and then it initializes the _log
member.
A working solution is moving the _log
initialization to the class top. This way the compiler first initializes _log
and then Foo
. However, we want to avoid that: In our organization, we have some coding rules that force us to sort code by visibility, so we first place public stuff at the class top, then, internal stuff, and finally private stuff.
Is there any way to tell the compiler the initialization order? If there is no way to do that, what would be, in your opinion, the best practices to fix this issue?
EDIT
I also tried to add a static constructor, but in that case the properties need to be calculated in the static constructor, just after initializing the _log
.