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 开发者_C百科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. :-)
Wow, such a good question. My first reaction was "of course that is ungood" ... but I typed it into VS2010 and seemed happy.
I found a possible answer for you (does that make me an answer proxy?) here: Using statement with a null object
If it was me, I would write a unit test to validate this behaviour so that if it every changed in the future the test will fail.
See ya
精彩评论