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?