Search code examples
c#null

Finding non null value using single line of code c#


I'm trying to find non null value from 3 strings using a single line code with some null checks in place.I'm getting NULL reference errors here as the c# is checking both sides of the "if" condition. How can I do this in a single line of code with all the null checks in place.

    string output = new String[] 
    {
        assessment.table1 == null ? "" : assessment.table1.Name, 
        assessment.table2 == null ? "" : assessment.table2.Name, 
        assessment.table3 == null ? "" : assessment.table3.Name 
    }
    .FirstOrDefault(s => s != "").ToString() ?? null

Open to other approaches to achieve this as well.


Solution

  • Assuming that assessment can't be null, but any table can we can put

    assessment.tableN?.Name
    

    to get either Name value or null if tableN. Then we can combine all three expresssions for table1 .. table3 into one with a help of ??

    var output = assessment.table1?.Name
              ?? assessment.table2?.Name
              ?? assessment.table3?.Name; 
    

    If you want to get empty string if all tables are null add one ?? more:

    var output = assessment.table1?.Name
              ?? assessment.table2?.Name
              ?? assessment.table3?.Name 
              ?? "";