0

I have the following calculated field in Vendor.cs:

public string FullAddress
    {
        get
        { 
            return VendorAddNum + " " + TLRoadDirection.Direction + " " + VendorAddName + " " + TLRoadType.RdType + " " + TLUnitTypeOne.UnitType + " " + VendorAddUnitOne + " " + TLUnitTypeTwo.UnitType + " " + VendorAddUnitTwo;
        }
    }

Here's the markup from the view for the field:

@Html.DisplayNameFor(model => model.FullAddress)

When one of my vendors doesn't have any address information, FullAddress is null, which causes me to get a null reference exception. How can I allow FullAddress to be null?

user1916528
  • 379
  • 4
  • 23

1 Answers1

1

Instead of concatenating all of the values, use string interpolation to better handle null values:

return $"{VendorAddNum} {TLRoadDirection.Direction} {VendorAddName} {TLRoadType.RdType} {TLUnitTypeOne.UnitType} {VendorAddUnitOne} {TLUnitTypeTwo.UnitType} {VendorAddUnitTwo}";

As an added bonus, the performance is a little better and the code is a little cleaner.


If you're using an older version of C#, you can use string.Format similarly:

return string.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}", VendorAddNum, TLRoadDirection.Direction, VendorAddName, TLRoadType.RdType, TLUnitTypeOne.UnitType, VendorAddUnitOne, TLUnitTypeTwo.UnitType, VendorAddUnitTwo);
David
  • 208,112
  • 36
  • 198
  • 279
  • Well I thought this was the solution, but I didn't notice that I had a value (typo) in the VendorAddNum field. When I remove that value, and all of the fields are null, I get the null reference exception again. Any idea of what I'm missing? – user1916528 May 27 '19 at 19:51
  • @user1916528: Where are you getting the exception? This code returns a string, not null. – David May 27 '19 at 19:52
  • When I attempt to go to the Index view I'm set back to the Vendor.cs file in VisualStudio. The null reference exception is on this calculated field in the model. – user1916528 May 27 '19 at 20:03
  • @user1916528: It doesn’t sound like this property is *returning* null, but that it’s relying on something *else* that’s null. There are 4 references to other properties (all starting with “TL”), one or more of them is likely null. – David May 27 '19 at 20:06
  • that was it, they were all causing the issue. So it looks like I have a different issue to solve. But your initial response was a terrific help and is the solution to my original question. – user1916528 May 27 '19 at 20:15