In May 2012, when you asked the question, I didn't see a simpler solution than the try ... catch you've provided. The only alternative - checking each part against null with "if" or "?" looked uglier (but is possibly a bit faster).
Either you had to write:
path = HttpContext!=null
? (HttpContext.Current!=null
? (HttpContext.Current.Request!=null
?(HttpContext.Current.Request.ApplicationPath!=null
? HttpContext.Current.Request.ApplicationPath
: null)
: null)
: null)
: null;
or:
if (HttpContext == null || HttpContext.Current == null
|| HttpContext.Current.Request == null
|| HttpContext.Current.Request.ApplicationPath == null)
path = null;
else
path = HttpContext.Current.Request.ApplicationPath;
both are doing it without exception handling. Note that both are using "shortcuts" to abort the check if any null value is found.
Update (December 2017):
Since C# Version 6 and higher, there is a better solution available, the so called Elvis
-Operator (also known as null-coalescing operator ?.
and x?[i]
for arrays), which you can use. The example above
path = HttpContext!=null
? (HttpContext.Current!=null
? (HttpContext.Current.Request!=null
?(HttpContext.Current.Request.ApplicationPath!=null
? HttpContext.Current.Request.ApplicationPath
: null)
: null)
: null)
: null;
looks much nicer this way:
path = HttpContext?.Current?.Request?.ApplicationPath;
which does exactly the same and is IMHO much more than "just" syntactical sugar. Combined with an appended ?? value
you can easily replace null
by some other value, e.g.
path = (HttpContext?.Current?.Request?.ApplicationPath) ?? "";
This makes the path
variable empty if no non-null value can be obtained.