I have seen how to initialize var to null. This does not help in my situation. I have
string nuller = null;
var firstModel = nuller;
if(contextSelectResult.Count() > 0)
firstModel = contextSelectResult.First();
I get error
Cannot implicitly convert type
‘SomeNamespace.Model.tableName’ to ‘string’.
I am trying to avoid try/catching InvalidOperation for First() when no first exists as its expensive. So, how can I get past the scope issue here?
Simply use
FirstOrDefault()instead. The whole point ofFirstOrDefaultis to return the first element of the sequence if it exists, or the default value of the element type (i.e. null for all reference types) otherwise.Note that in other cases where you wish to check for the existence of any elements, using
Any()can sometimes be more efficient thanCount() > 0– it depends on the exact context, but IMO it’s a simpler way of expressing what you’re looking for anyway.