Search code examples
c#null-coalescing-operator

Is there a cleaner way to set this anonymous class property?


I am returning an anonymous class:

var clients = from c in this.ClientRepository.SearchClientByTerm(term, 10)
    select new
    {
       id = c.Id,
       line1 = c.Address.Line1 ?? "Unknown Information ..."
    };

The problem is Address is nullable which means if it is null it explodes into a million pieces.

The most elegant solution i could think of was this...

    line1 = c.Address != null && c.Address.Line1 != null 
               ? c.Address.Line1 : "Unknown Information ..."

Is there a better way?, i don't like losing the ability to use the null-coalescing operator and then having to check if null.


Solution

  • The only cleaner way I can think of is to modify the getter of the Address property to never return null, or have the constructor always initialize the Address. Otherwise you always need to check for null.