The Danger of Null Values
I made a goof ball mistake today. I was using LINQ to query a List<> and return the ToString() of the result. As usual I was using FirstOrDefault() and I simply added .ToString() to the end of it.
fieldValue = (from d in customFields where d.CustomFieldId == fieldId select d.data).FirstOrDefault().ToString();
Of course things worked swimmingly until the Default (null) was hit. At that point I got an Object not set to an instance error. I had to laugh at myself.
var fieldData = (from d in customFields where d.CustomFieldId == fieldId select d.data).FirstOrDefault(); fieldValue = fieldData != null ? fieldData.ToString() : "";
Posted on January 12, 2015, in Bits, Debugging and tagged LINQ. Bookmark the permalink. Leave a comment.
Leave a comment
Comments 0