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 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.
Step
must be an extension method, as was my guess in the comment.
Otherwise either your compiler is mutilated or you're hallucinating. :-)
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