开发者

NullReferenceException handling in in-line asp.net code

开发者 https://www.devze.com 2023-02-10 22:58 出处:网络
I have some inline code in an aspx file that executes: <dd><%=encode(Listing.Address.Line1) %> </dd>

I have some inline code in an aspx file that executes:

<dd><%=  encode(Listing.Address.Line1) %> </dd>

Problem is, under certain circumstances the Listing object will be null and therefore references to properties such as Address will throw an exception. How do I handle that exception? I basically want to ignore it: catch it, and then proceed with regu开发者_运维知识库lar execution/rendering of page.


Do a null check. It is almost always better to test for the conditions of an exception that you expect might happen rather than handle it. The runtime has to do more work to throw and handle an exception than it does to just test for it in the first place and deal with it accordingly.

<%= encode(Listing != null && Listing.Address != null ? Listing.Address.Line1 : string.Empty) %> 

And be sure to check address just in case. Short circuiting is your friend, the order matters in the &&ing.

Without seeing a broader picture, I would suggest that your viewmodel, if you have one, has a method that does this automatically for you. This kind of stuff gets ugly in the view if you have it everyplace.


Assuming the problem to be fairly simple where Listing isn't null, and therefore, all it underlying attributes aren't null either you can type something like this:

<%= encode( (Listing ?? (new Listing(AddressObj))).Address.Line1 ) %>

Your can write the Listing class here with a constructor such that Address.Line1 will always have value.

Now if your problem is fairly complex, where in you Listing object may have a valid instance but its underlying attribute may not: the best way is to wrap the encode method into another method or property which will return the expected result, and call that in the markup.

public string EncodedAddress
{
    get
    {
        if (Listing == null)
            return string.Empty;
        if (Listing.Address == null)
            return string.Empty;
        return encode(Listing.Address.Line1);
    }
}

In the markup you do something like:

<%= EncodedAddress %>


Use this

<%= if(Listing.Address.Line1 != null)
      { 
         encode(Listing.Address.Line1)
      }
%> 
0

精彩评论

暂无评论...
验证码 换一张
取 消