Tuesday, 17 September 2013

Avoiding SingleOrDefault null reference exception

Avoiding SingleOrDefault null reference exception

I'm adding parameters to insert information into a database and ran into a
a potential null reference exception. By using the SingleOrDefault LINQ
expression, I thought if an instance had no Tag called "Name" the Tag
would default to a null value. This is true as long as the instance has
some sort of Tag. If the instance has no tags at all, a null reference
exception occurs. It's a rare occurrence, but I still need a better way to
handle it. Is there a better way to solve this than catching the
exception?
cmd.Parameters.AddWithValue("@Name", runningInstance.Tag.SingleOrDefault(t
=> t.Key == "Name").Value);

No comments:

Post a Comment