Checking for null before ToString()

前端 未结 12 1494
暖寄归人
暖寄归人 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: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();
    

提交回复
热议问题