Nous utilisons des cookies pour améliorer votre expérience de navigation. En savoir plus
Accepter
to the top
close form

Remplissez le formulaire ci‑dessous en 2 étapes simples :

Vos coordonnées :

Étape 1
Félicitations ! Voici votre code promo !

Type de licence souhaité :

Étape 2
Team license
Enterprise licence
** En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité
close form
Demandez des tarifs
Nouvelle licence
Renouvellement de licence
--Sélectionnez la devise--
USD
EUR
* En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité

close form
La licence PVS‑Studio gratuit pour les spécialistes Microsoft MVP
close form
Pour obtenir la licence de votre projet open source, s’il vous plait rempliez ce formulaire
* En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité

close form
I am interested to try it on the platforms:
* En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité

close form
check circle
Votre message a été envoyé.

Nous vous répondrons à


Si vous n'avez toujours pas reçu de réponse, vérifiez votre dossier
Spam/Junk et cliquez sur le bouton "Not Spam".
De cette façon, vous ne manquerez la réponse de notre équipe.

>
>
>
V3166. Calling the 'SingleOrDefault' me…
menu mobile close menu
Analyzer diagnostics
General Analysis (C++)
General Analysis (C#)
General Analysis (Java)
Micro-Optimizations (C++)
Diagnosis of 64-bit errors (Viva64, C++)
Customer specific requests (C++)
MISRA errors
AUTOSAR errors
OWASP errors (C#)
Problems related to code analyzer
Additional information
toggle menu Contents

V3166. Calling the 'SingleOrDefault' method may lead to 'InvalidOperationException'.

24 Nov 2020

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: