C# constructor and constants mystery
-
25-05-2021 - |
Pergunta
why would a static constructor throw exception when it references to a const string in another class.
class MyClass
{
static MyClass()
{
ExamineLog();
}
static ExamineLog()
{
FilePath = HttpContext.Current.Server.MapPath(Helper.LogConfiguration);
}
}
class Helper
{
public const string LogConfiguration= "\rootpath\counters.txt";
}
The exception thrown is object reference not set to an instance of an object. The stack trace points to the line where attempt is made to read the constant value. Any thoughts?
Solução
Thoughts:
HttpContext
might be nullHttpContext.Current
might be nullHttpContext.Current.Server
might be null
Further thoughts:
Current
is a static property of the HttpContext
class, so HttpContext
is not an object reference, and it cannot be null. If you want to simplify your debugging, you can change the code like this (I'm assuming that ExamineLog
should have been declared as a void method):
static void ExamineLog()
{
var context = HttpContext.Current;
var server = context.Server;
FilePath = server.MapPath(Helper.LogConfiguration);
}
Outras dicas
my first bet is a bad string...
"\rootpath\counters.txt" // => "\r" is carriage return
So MapPath fails.
My guess is that the HttpContext.Current is null in the context of a static constructor. It's been a while since I was knee-deep in ASP.NET, but IIRC, the HttpContext.Current won't be setup unless you're in the request-response life cycle of a page. I don't know when static constructors are necessarily executed in an ASP.NET application (technically, should be when first accessed by code) and in your case, it could easily be in a context outside of this page life cycle.
I doubt the null reference is coming from your const reference: const reference is inserted as a literal value/string at compile-time so there should be no run-time null reference exception thrown.