Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding SingleOrDefault null reference exception

Tags:

c#

linq

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);
like image 650
EFeit Avatar asked Dec 21 '22 00:12

EFeit


1 Answers

The only good way is to reconstruct your query a bit:

instance.Tag.Where(t => t.Key == "Name").Select(T => T.Value).SingleOrDefault();

That will do the trick.


Update:

I suspect your Tag property is of type IDictionary<,>. In that case, the best option to retrieve a value is:

if (instance.Tag.TryGetValue("Name", out TValue value))
{
    // We have the value in the value. :)
}
else
{
    // We don't.
}
like image 184
AgentFire Avatar answered Dec 26 '22 20:12

AgentFire