Search code examples
c#stringstring-building

Building a string using ternary operations


I'm trying to build a string using ternary operations and pass it to a cell of an Excel file. Here is my code:

            ws.Rows[index].Cells[24].Value = i.IliskiliCokluIsler.Count == 0 ?

                i.IliskiliMahalle.MahalleAdi != null ? i.IliskiliMahalle.MahalleAdi + " Mahallesi" : "" + 
                i.IliskiliYerGorme.BulvarCadde != null ? i.IliskiliYerGorme.BulvarCadde + " Cadde" : "" +
                i.IliskiliYerGorme.Sokak != null ? i.IliskiliYerGorme.Sokak + " Sokak" : "" + 
                i.IliskiliYerGorme.BinaNo != null ? "Bina no : " + i.IliskiliYerGorme.BinaNo : "" + 
                i.IliskiliYerGorme.KatNo != null ? i.IliskiliYerGorme.KatNo + " Kat" : "" +
                i.IliskiliIlce.IlceAdi + i.IliskiliSehir.SehirAdi : "";

I know that i.IliskiliIlce.IlceAdi and i.IliskiliSehir.SehirAdi and i.IliskiliYerGorme.KatNo are not null. When I run the code I only get

X Mahallesi

Namely I can't get other entities whether or not they are null. Where am I doing wrong? Is the idea of generating string using ternary operations like that is wrong? How can I do it in the right way? Thanks.


Solution

  • This is almost certainly down to operator precedence; + has a higher precedence than ?:, that is, if we take just the first couple of lines:

    i.IliskiliMahalle.MahalleAdi != null ? i.IliskiliMahalle.MahalleAdi + " Mahallesi" : "" + 
    i.IliskiliYerGorme.BulvarCadde != null ? i.IliskiliYerGorme.BulvarCadde + " Cadde" : ""
    

    It will be evaluating them as:

    i.IliskiliMahalle.MahalleAdi != null ? i.IliskiliMahalle.MahalleAdi + " Mahallesi" :
        ("" + i.IliskiliYerGorme.BulvarCadde != null ? 
            i.IliskiliYerGorme.BulvarCadde + " Cadde" : "")
    

    Which is not what you want. You can fix this by surrounding each of your lines with parentheses:

    ws.Rows[index].Cells[24].Value = i.IliskiliCokluIsler.Count == 0 ?
    (i.IliskiliMahalle.MahalleAdi != null ? i.IliskiliMahalle.MahalleAdi + " Mahallesi" : "") + 
    (i.IliskiliYerGorme.BulvarCadde != null ? i.IliskiliYerGorme.BulvarCadde + " Cadde" : "") +
    (i.IliskiliYerGorme.Sokak != null ? i.IliskiliYerGorme.Sokak + " Sokak" : "") + 
    (i.IliskiliYerGorme.BinaNo != null ? "Bina no : " + i.IliskiliYerGorme.BinaNo : "") + 
    (i.IliskiliYerGorme.KatNo != null ? i.IliskiliYerGorme.KatNo + " Kat" : "") +
    (i.IliskiliIlce.IlceAdi + i.IliskiliSehir.SehirAdi : "");
    

    If this is an often-run bit of code, however, I would consider using a StringBuilder instead.