Checking for null before ToString()

前端 未结 12 1530
暖寄归人
暖寄归人 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:59

    How about using an auxiliary method like this:

    attribs.something = getString(
        entry.Properties["something"].Value, 
        attribs.something);
    
    static String getString(
        Object obj,
        String defaultString)
    {
        if (obj == null) return defaultString;
        return obj.ToString();
    }
    

    Alternatively, you could use the ?? operator:

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

    (note the redundant ToString() call when the value is null)

提交回复
热议问题