Elegant way to avoid NullReferenceException in C#

前端 未结 4 2016
傲寒
傲寒 2020-12-18 03:09

I want to do this

var path = HttpContext.Current.Request.ApplicationPath;

If any of the Properties along the way is null, i want path to be

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-18 03:59

    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.

提交回复
热议问题