In May 2012, when you asked a question, I did not see a simpler solution than trying ... to catch you. The only alternative is to check each part against zero with "if" or "?" looked ugly (but maybe a little faster).
Or 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 do this without exception handling. Note that both methods use shortcuts to abort the check if a null value is found.
Update (December 2017): Since C # Version 6 and above , a better solution is available, the so-called Elvis Operator (also known as the zero-coalescing operator ?. And x?[i] for arrays), which you can use. 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;
It looks much better:
path = HttpContext?.Current?.Request?.ApplicationPath;
which does the same thing and IMHO is much more than just syntactic sugar. Combined with the added ?? value ?? value you can easily replace null with another value, for example.
path = (HttpContext?.Current?.Request?.ApplicationPath) ?? "";
This makes the path variable empty if a nonzero value cannot be obtained.
Matt
source share