Checking for null before ToString()

前端 未结 12 1523
暖寄归人
暖寄归人 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: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;
        }
    }
    

提交回复
热议问题