Elegant way to avoid NullReferenceException in C#

前端 未结 4 2024
傲寒
傲寒 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条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-18 04:03

    The shortest and most performant path is to perform the null check against every level. For reuse you can wrap that code up into a helper function or perhaps an extension method. This will let you safely access it via that function, but still consistently perform the null check.

    Example:

    public void DoSomething()
    {
      // Get the path, which may be null, using the extension method
      var contextPath = HttpContext.Current.RequestPath;
    }
    
    
    public static class HttpContextExtensions
    {
      public static string RequestPath(this HttpContext context)
      {
        if (context == null || context.Request == null)
        {
          return default(string);
        }
    
        return context.Request.ApplicationPath;
      }
    }
    

提交回复
热议问题