Search code examples
stringreplacenullreferenceexceptionwebmatrixwebgrid

WebGrid Replace function in string null reference exception


I keep getting

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 54:                        string review = item.Review;
Line 55:                        //review = review.Replace("\r\n", "<br/>");
Line 56:                        return review.Replace("\r\n", "<br/>");
Line 57:                     }),
Line 58:                     grid.Column(format: @<a href="~/DeleteMovie?id=@item.ID">Delete</a>)

....................... Line: 56

When I try to use the Replace function for the string review. I create and set the instance of review on line 54 and it will output the text I am expecting. But when I try to do a replace I get this error. Why?


Solution

  • Line 54 does not create an instance of review, rather it just points to the item.Review value that may or may not be null.

    Presumably in this case item.Review is itself null, and thus review is also null.

    One thing you could do to work around this is change line 54 to:

    string review = item.Review ?? "";
    

    This will ensure that review is never null. It'll either have the contents of item.Review or it will be an empty string (which is not null).