V3166. Calling the 'SingleOrDefault' method may lead to 'InvalidOperationException'.
The analyzer has detected a situation where the 'SingleOrDefault' method may be called without a predicate on a collection that has more than one element. Such a call will lead to throwing an exception of the 'System.InvalidOperationException' type.
The programmer may have wrong assumptions about this method's behavior because of other 'OrDefault' methods' behavior. For example, the methods 'FirstOrDefault', 'LastOrDefault', and 'ElementAtOrDefault' return a 'default' value of the type of elements in a collection when the operation cannot be accomplished (because the collection is empty, there is no element matching the predicate, and so on). Similarly, the 'SingleOrDefault' method also returns the 'default' value when called on an empty collection, but throws an exception if there is more than one element in the collection. This detail may be unknown to the programmer.
Consider the following example:
IEnumerable<State> GetStates()
{
var states = new List<State>();
if (usualCondition)
states.Add(GetCustomState());
if (veryRareCondition)
states.Add(GetAnotherState());
return states;
}
void AnalyzeState()
{
....
var state = GetStates().SingleOrDefault();
....
}
Not knowing the specifics of the 'SingleOrDefault' method's behavior, the developer intended the 'state' variable to store the value returned from the 'GetStates' method when the collection contains only one element, or 'default' otherwise (the collection has no elements or more than one element). However, if both the usual and the very rare condition (the variables 'usualCondition' and 'veryRareCondition') happen to be true at the same time, 'GetStates' will return a collection of two elements. In this case, an exception will be thrown instead of writing the 'default' value to 'state'.
The 'AnalyzeState' method can be fixed in the following way:
void AnalyzeState()
{
....
var states = GetStates();
var state = states.Count() == 1 ? states.First()
: default;
....
}
This diagnostic is classified as: