Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the '{' throw a NullReferenceException in a static method?

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.

like image 673
Zachary Yates Avatar asked Aug 26 '10 13:08

Zachary Yates


Video Answer


1 Answers

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.

like image 164
Joel Coehoorn Avatar answered Sep 20 '22 11:09

Joel Coehoorn