Checking for null before ToString()

前端 未结 12 1500
暖寄归人
暖寄归人 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 03:16

    Adding an empty string to an object is a common idiom that lets you do null-safe ToString conversion, like this:

    attribs.something = ""+entry.Properties["something"].Value;
    

    When entry.Properties["something"].Value is null, this quietly returns an empty string.

    Edit: Starting with C# 6 you can use ?. operator to avoid null checking in an even simpler way:

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

提交回复
热议问题