Checking for null before ToString()

前端 未结 12 1524
暖寄归人
暖寄归人 2020-12-01 02:21

Here\'s the scenario...

if (entry.Properties[\"something\"].Value != null)
  attribs.something = entry.Properties[\"something\"].Value.ToString();
<         


        
12条回答
  •  时光说笑
    2020-12-01 02:54

    As a variation to RexM's answer:

    attribs.something = (entry.Properties["something"].Value ?? attribs.something).ToString()
    

    The only downside would be that the attribs.something would be assigned a value (itself, in this example) even if entry.Properties["something"].Value was null - which could be expensive if the .something property did some other processing and/or this line executes a lot (like in a loop).

提交回复
热议问题