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() : "";
Advertisements

About SheldonS

Web developer for over 15 years mainly with Microsoft technologies from classic ASP to .NET 4. Husband, father, and aspiring amateur photographer.

Posted on January 12, 2015, in Bits, Debugging and tagged . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: