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?
It’s absolutely not OK if
profileris null unlessprofiler.Stepis actually an extension method. Theusingstatement doesn’t affect that.As it turns out, the extension method part is exactly what’s going on. Lines 584-587 of MiniProfiler.cs:
That’s how it’s okay for
profiler.Stepto be called whenprofileris null. It’s not an instance method – the call translates to:It’s fine for
profiler.Stepto return null, as per the second part of your question.