This one is sort of esoteric. I ran into a NullReferenceException while trying to open a form (in the winforms designer) in a winforms project in visual studio 2008. The stack trace points to the fourth line of the following code:
public static class Logger
{
public static void LogMethodEnter()
{
var frame = new StackFrame(1);
var method = frame.GetMethod();
Trace.TraceInformation("{0}.{1}.{2}()", method.DeclaringType.Namespace, method.DeclaringType.Name, method.Name);
Trace.Indent();
}
public static void LogMethodExit()
{
Trace.Unindent();
}
}
...meaning the line with the opening curly brace. I've run into the same issue (but not involving the winforms designer) on other projects, and I think it was a threading related issue, but I don't have the code to replicate it.
Why does this happen and why does the exception stack trace point to the line with the curly brace?
Clarification: The null reference exception only happens in the winforms designer. When the application is run, it doesn't throw that error.
I'm guessing that the line numbers are off (the actual reason for that is not as important) and the exception is actually thrown by this expression:
method.DeclaringType.Namespace
And the reason you might see a NullReference exception there is because the new StackFrame(1)
expression a couple lines previous can sometimes return an empty frame. An empty frame means the call to .GetMethod()
will return null, and there you go.
The reason you sometimes get an empty frame is that the just-in-time compiler can choose to inline short, repeatedly-called methods like the one in your code. That will throw off your call stack so at best you get a higher-level method than you intended, or at worst (in your Main method) there is no higher method and you get null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With