Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling methods on a null reference in the context of a using clause is OK?

I was looking at the mvc-mini-profiler designed by the Stack Overflow team on Google Code and one thing on the getting started page struck me as particularly strange:

var profiler = MiniProfiler.Current; // it's ok if this is null

using (profiler.Step("Set page title"))
{
    ViewBag.Title = "Home Page";
}

How can it be "ok" if profiler is null? It seems to me that calling Step would throw a NullReferenceException. In all my years of programming C# I've never known calling a method on a null reference in any context to be "ok". Is this a special case in the context of a using clause?

I can understand this being OK (didn't know it was, but apparently it is?):

using (null)
{
    ...
}

but calling a method on a null reference seems like it should throw an exception regardless of whether it's in a using clause. Can someone please explain how such a construct is translated behind the scenes, so I can understand why it is OK to do this?

like image 617
Jake Petroules Avatar asked Jul 10 '11 06:07

Jake Petroules


2 Answers

It's absolutely not OK if profiler is null unless profiler.Step is actually an extension method. The using statement doesn't affect that.

As it turns out, the extension method part is exactly what's going on. Lines 584-587 of MiniProfiler.cs:

public static IDisposable Step(this MiniProfiler profiler, string name,
                               ProfileLevel level = ProfileLevel.Info)
{
    return profiler == null ? null : profiler.StepImpl(name, level);
}

That's how it's okay for profiler.Step to be called when profiler is null. It's not an instance method - the call translates to:

MiniProfilerExtensions.Step(profiler, ...);

It's fine for profiler.Step to return null, as per the second part of your question.

like image 154
Jon Skeet Avatar answered Nov 16 '22 00:11

Jon Skeet


Step must be an extension method, as was my guess in the comment.

Otherwise either your compiler is mutilated or you're hallucinating. :-)

like image 5
user541686 Avatar answered Nov 16 '22 01:11

user541686