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.

>
>
>
V3149. Dereferencing the result of 'as'…
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

V3149. Dereferencing the result of 'as' operator can lead to NullReferenceException.

04 Déc 2019

The analyzer has detected an unsafe dereference of the value resulting from type conversion using the 'as' operator.

Consider the following contrived example:

void Foo()
{
  BaseItem a = GetItem();
  var b = a as SpecificItem;
  b.Bar();
}

The type of the value returned from the method may be different from the type we want to cast to. In that case, casting between the types using the 'as' operator will result in writing the value null to the variable 'b'. Even though no error will occur at the moment of the cast itself, further use of this variable without a prior null check will lead to raising a 'NullReferenceException'. The fixed code:

void Foo()
{
  BaseItem a = GetItem();
  var b = a as SpecificItem;
  b?.Bar();
}

If you are sure that the variable to which the 'as' operator is applied will always be successfully cast from the runtime type to the specified type, use the explicit cast operator:

void Foo()
{
  BaseItem a = GetItem();
  var b = (SpecificItem)a;
  b.Bar();
}

If the program's behavior changes later and the 'GetItem' method is no longer guaranteed to return a value convertible to the specified type, an invalid cast will raise an 'InvalidCastException', allowing you to quickly identify the problem spot. In contrast, using the 'as' operator will lead to raising a 'NullReferenceException' further in the code when attempting to dereference the variable resulting from an invalid cast and having the value null, and this may not happen until execution gets far from the failed cast, say, in some other method, thus making it difficult to find and fix the bug.

This diagnostic also points out possible typos in type checks:

void Foo()
{
  IDisposable a = GetItem();
  if(a is NonSpecificItem)
  {
    var b = a as SpecificItem;
    b.Bar();
  }
}

In this example, the types SpecificItem and NonSpecificItem are not related, so the cast will return a null pointer. To prevent typos like that from breaking the program, you can implement the check using the Is Type Pattern syntax provided by C# 7.0:

void Foo()
{
  IDisposable a = GetItem();
  if(a is NonSpecificItem item)
  {
    item.Bar();
  }
}

The following snippet is taken from a real open-source project:

....
FuelDefinition = MyDefinitionManager.Static.GetPhysicalItemDefinition(FuelId);
MyDebug.AssertDebug(FuelDefinition != null);
....
String constraintTooltip = FuelDefinition.DisplayNameText;

The 'GetPhysicalItemDefinition' method returns an object of type MyPhysicalItemDefinition retrieved from an array of objects of the basic type 'MyDefinitionBase':

public MyPhysicalItemDefinition GetPhysicalItemDefinition(MyDefinitionId id)
{
  ....
  return m_definitions.m_definitionsById[id] as MyPhysicalItemDefinition;
}

The call of the 'GetPhysicalItemDefinition' method is followed by a null check (MyDebug.AssertDebug) of the value resulting from the cast, which suggests that the method may return an object of an incompatible type. This check, however, will work only in the Debug version. In the Release version, the failed cast will result in null dereference further in the code (FuelDefinition.DisplayNameText).

This diagnostic is classified as: