Empty string if null

后端 未结 4 1383
南方客
南方客 2020-12-08 14:09

I have this in my code:

SelectList(blah, \"blah\", \"blah\", cu.Customer.CustomerID.ToString())

It gives a error when it returns null, how

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 14:47

    (C# 2.0 - C# 5.0)

    The ternary operator works, but if you want even shorter expression working on arbitrary objects you can use:

    (myObject ?? "").ToString()
    

    Here is real-life example from my code:

     private HtmlTableCell CreateTableCell(object cellContents)
     {
         return new HtmlTableCell()
         {
             InnerText = (cellContents ?? "").ToString()             
         };
     }
    

提交回复
热议问题