Ways to call in null reference in context of use clause is ok?

I was looking at the mvc-mini-profiler developed by the Qaru team in Google Code, and one thing at the beginning of my work is especially strange:

var profiler = MiniProfiler.Current; // it ok if this is null using (profiler.Step("Set page title")) { ViewBag.Title = "Home Page"; } 

How can this be “normal” if the profiler is null? It seems to me that calling Step will NullReferenceException . For all the years of C # programming, I never called a method on a null reference in any context "good." Is this a special case in the context of a usage proposal?

I can understand that this is OK (I didn’t know what it was, but apparently this is so?):

 using (null) { ... } 

but calling the method in a null reference seems like it should throw an exception, regardless of whether it is in the use clause. Can someone explain how such a design is broadcast backstage, so I can understand why this is normal?

+8
null c # nullreferenceexception
source share
3 answers

This is absolutely not normal if profiler is null, if profiler.Step is not actually an extension. The using statement does not affect this.

As it turns out, part of the extension method is exactly what happens. 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); } 

The way it is normal for profiler.Step be called when profiler is null. This is not an instance method - the call translates to:

 MiniProfilerExtensions.Step(profiler, ...); 

It is normal for profiler.Step to return null according to the second part of your question.

+12
source share

Step should be an extension method , as expected in the comment.

Otherwise, your compiler is crippled or you are hallucinating. :-)

+5
source share

Wow, such a good question. My first reaction was “of course, this is not good” ... but I typed it in VS2010 and looked happy.

I found a possible answer for you (does this make me a proxy response?) Here: Using a null object operator

If it were me, I would write unit test to test this behavior, so that if it changes in the future, the test will fail.

See ya

+1
source share

All Articles