Checking for null before ToString()

前端 未结 12 1487
暖寄归人
暖寄归人 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
    Convert.ToString(entry.Properties["something"].Value);
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-12-01 02:55

    If you are targeting the .NET Framework 3.5, the most elegant solution would be an extension method in my opinion.

    public static class ObjectExtensions
    {
        public static string NullSafeToString(this object obj)
        {
            return obj != null ? obj.ToString() : String.Empty;
        }
    }
    

    Then to use:

    attribs.something = entry.Properties["something"].Value.NullSafeToString();
    
    0 讨论(0)
  • 2020-12-01 02:58

    Can you not do:

    attribs.something = entry.Properties["something"].Value as string;
    
    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-12-01 03:08

    In C# 6.0 you can do it in a very elegant way:

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

    And here is an article about new null-conditional operator.

    0 讨论(0)
提交回复
热议问题