Checking for null before ToString()

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

    To do precisely what you're trying to do a helper method can always be used:

    CopyIfNotNull(entry.Properties["something"].Value, out attribs.something);
    
    void CopyIfNotNull(string src, out string dest)
    {
      if(src != null)
        dest = src;
    }
    
    0 讨论(0)
  • 2020-12-01 03:10
    attribs.something  = string.Format("{0}",entry.Properties["something"].Value)
    
    0 讨论(0)
  • 2020-12-01 03:12

    Update 8 years later (wow!) to cover c# 6's null-conditional operator:

    var value = maybeNull?.ToString() ?? String.Empty;
    

    Other approaches:

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

    I've also used this, which isn't terribly clever but convenient:

    public static string ToSafeString(this object obj)
    {
        return (obj ?? string.Empty).ToString();
    }
    
    0 讨论(0)
  • 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();
    //                                                     ^^
    
    0 讨论(0)
  • 2020-12-01 03:20
    attribs.something = String.Format("{0}", entry.Properties["something"].Value);
    

    Not sure about performance though...

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

    Is it somehow possible to do something like Dale Ragan's answer above, but overriding ToString() instead of creating a new NullSafeToString() method? I'd like this (or returning "null") to be the default behaviour. The compiler (Visual C# 2010 Express) doesn't complain when I add the following method to public static class ObjectExtensions, but the method doesn't get called...

    public static String ToString(this Object obj)
    {
        if (obj == null)
        {
            return "null";
        }
        else
        {
            return obj.GetType().Name;
        }
    }
    
    0 讨论(0)
提交回复
热议问题