Our website uses cookies to enhance your browsing experience.
Accept
to the top
close form

Fill out the form in 2 simple steps below:

Your contact information:

Step 1
Congratulations! This is your promo code!

Desired license type:

Step 2
Team license
Enterprise license
** By clicking this button you agree to our Privacy Policy statement
close form
Request our prices
New License
License Renewal
--Select currency--
USD
EUR
* By clicking this button you agree to our Privacy Policy statement

close form
Free PVS‑Studio license for Microsoft MVP specialists
* By clicking this button you agree to our Privacy Policy statement

close form
To get the licence for your open-source project, please fill out this form
* By clicking this button you agree to our Privacy Policy statement

close form
I am interested to try it on the platforms:
* By clicking this button you agree to our Privacy Policy statement

close form
check circle
Message submitted.

Your message has been sent. We will email you at


If you do not see the email in your inbox, please check if it is filtered to one of the following folders:

  • Promotion
  • Updates
  • Spam

Webinar: C++ semantics - 06.11

>
>
>
Examples of errors detected by the V304…

Examples of errors detected by the V3042 diagnostic

V3042. Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the same object.


Xamarin.Forms

V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the Element object Xamarin.Forms.Platform.WinRT MasterDetailPageRenderer.cs 288


void UpdateTitle()
{
  if (Element?.Detail == null)
    return;

   ((ITitleProvider)this).Title =
     (Element.Detail as NavigationPage)
       ?.CurrentPage?.Title ?? Element.Title
                            ?? Element?.Title;
}

.NET Core Libraries (CoreFX)

V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'sym' object SymbolStore.cs 56


private static void InsertChildNoGrow(Symbol child)
{
  ....
  while (sym?.nextSameName != null)
  {
    sym = sym.nextSameName;
  }

  Debug.Assert(sym != null && sym.nextSameName == null);
  sym.nextSameName = child; // <=
  ....
}

.NET Core Libraries (CoreFX)

V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'property' object JsonClassInfo.AddProperty.cs 179


internal JsonPropertyInfo CreatePolymorphicProperty(....)
{
  JsonPropertyInfo runtimeProperty
    = CreateProperty(property.DeclaredPropertyType,    // <=
                     runtimePropertyType,
                     property.ImplementedPropertyType, // <=
                     property?.PropertyInfo,           // <=
                     Type,
                     options);
  ....
}

Azure PowerShell

V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'imageAndOsType' object VirtualMachineScaleSetStrategy.cs 81


internal static ResourceConfig<VirtualMachineScaleSet>
CreateVirtualMachineScaleSetConfig(...., ImageAndOsType imageAndOsType, ....)
{
  ....
  VirtualMachineProfile = new VirtualMachineScaleSetVMProfile
  {
    OsProfile = new VirtualMachineScaleSetOSProfile
    {
        ....,
        WindowsConfiguration =
          imageAndOsType.CreateWindowsConfiguration(),  // <=
        ....,
    },
    StorageProfile = new VirtualMachineScaleSetStorageProfile
    {
        ImageReference = imageAndOsType?.Image,  // <=
        DataDisks = DataDiskStrategy.CreateVmssDataDisks(
          imageAndOsType?.DataDiskLuns, dataDisks)  // <=
    },
  },
  ....
}

Azure PowerShell

V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'existingContacts' object RemoveAzureKeyVaultCertificateContact.cs 123


public override void ExecuteCmdlet()
{
  ....
  List<PSKeyVaultCertificateContact> existingContacts;

  try
  {
    existingContacts = this.DataServiceClient.
                       GetCertificateContacts(VaultName)?.ToList();
  }
  catch (KeyVaultErrorException exception)
  {
    ....
    existingContacts = null;
  }

  foreach (var email in EmailAddress)
  {
    existingContacts.RemoveAll(....);  // <=
  }
  ....
}

osu!

V3042 [CWE-476] Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'val.NewValue' object TournamentTeam.cs 41


public TournamentTeam()
{
  Acronym.ValueChanged += val =>
  {
    if (....)
      FlagName.Value = val.NewValue.Length >= 2     // <=
        ? val.NewValue?.Substring(0, 2).ToUpper()
        : string.Empty;
  };
  ....
}

Similar errors can be found in some other places:

  • V3042 [CWE-476] Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'val.NewValue' object TournamentTeam.cs 48

osu!

V3042 [CWE-476] Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'api' object SetupScreen.cs 77


private void reload()
{
  ....
  new ActionableInfo
  {
    Label = "Current User",
    ButtonText = "Change Login",
    Action = () =>
    {
      api.Logout();     // <=
      ....
    },
    Value = api?.LocalUser.Value.Username,
    ....
  },
  ....
}

Ryujinx

V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'data' object Client.cs 254


public void ReceiveLoop(int clientId)
{
    ....
    byte[] data = Receive(clientId);

    if (data.Length == 0)
    {
        continue;
    }
    ....
}

private byte[] Receive(int clientId, int timeout = 0)
{
    ....
    var result = _client?.Receive(ref endPoint);

    if (result.Length > 0)
    {
        ....
    }

    return result;
    ....
}

LINQ to DB

V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the '_update' object SqlUpdateStatement.cs 60


public override ISqlTableSource? GetTableSource(ISqlTableSource table)
{
  ....
  if (table == _update?.Table)
    return _update.Table;
  ....
}

DotNetNuke

V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'module.DesktopModule' object Converters.cs 67


public static ModuleItem ConvertToModuleItem(ModuleInfo module)
  => new ModuleItem
{
  Id = module.ModuleID,
  Title = module.ModuleTitle,
  FriendlyName = module.DesktopModule.FriendlyName, // <=
  EditContentUrl = GetModuleEditContentUrl(module),
  EditSettingUrl = GetModuleEditSettingUrl(module),
  IsPortable = module.DesktopModule?.IsPortable,    // <=
  AllTabs = module.AllTabs,
};

DotNetNuke

V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'PortalSettings.Current' object PagesMenuController.cs 47


public IDictionary<string, object> GetSettings(MenuItem menuItem)
{
  var settings = new Dictionary<string, object>
  {
    { "canSeePagesList",
      this.securityService.CanViewPageList(menuItem.MenuId) },

    { "portalName",
      PortalSettings.Current.PortalName },              // <=

    { "currentPagePermissions",
      this.securityService.GetCurrentPagePermissions() },

    { "currentPageName",
      PortalSettings.Current?.ActiveTab?.TabName },     // <=

    { "productSKU",
      DotNetNukeContext.Current.Application.SKU },

    { "isAdmin",
      this.securityService.IsPageAdminUser() },

    { "currentParentHasChildren",
      PortalSettings.Current?.ActiveTab?.HasChildren },  // <=

    { "isAdminHostSystemPage",
      this.securityService.IsAdminHostSystemPage() },
  };

  return settings;
}

Unity C# reference source code

V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'version' object UpmPackageDocs.cs 38


public static string FetchBuiltinDescription(....)
{
  return string.IsNullOrEmpty(version?.packageInfo?.description) ?
    string.Format(L10n.Tr(....), version.displayName) :
    version.packageInfo.description.Split(....)[0];
}

Power-Fx

V3042 [CWE-476] Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'mergeExpandValue' object TabularDataQueryOptions.cs 282


internal bool AppendExpandQueryOptions(ExpandQueryOptions mergeExpandValue)
{
  ....
  ExpandQueryOptions[mergeExpandValue.ExpandInfo.ExpandPath] =
    mergeExpandValue?.Clone();
  return true;
}

Power-Fx

V3042 [CWE-476] Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'node' object ResolvedObjectHelpers.cs 45


public static FormulaValue ResolvedObjectError(ResolvedObjectNode node)
{
    return new ErrorValue(node.IRContext, new ExpressionError()
    {
        Message = $"Unrecognized symbol {node?.Value?.GetType()?.Name}".Trim(),
        Span = node.IRContext.SourceContext,
        Kind = ErrorKind.Validation
    });
}

Similar errors can be found in some other places:

  • V3042 [CWE-476] Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'node' object ResolvedObjectHelpers.cs 48

Power-Fx

V3042 [CWE-476] Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'other.Fields' object FormulaTypeSchema.cs 118


public override bool Equals(object o)
{
  return o is FormulaTypeSchema other &&
    Type.Equals(other.Type) &&
    Description == other.Description &&
    Help == other.Help &&
    Fields?.Count() == other.Fields?.Count() &&
    (Fields?.All(
      (thisKvp) => other.Fields.TryGetValue(thisKvp.Key, out var otherValue) &&
      (thisKvp.Value?.Equals(otherValue) ?? otherValue == null)) ?? true);
}

WolvenKit

V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'settingsManager' object App.xaml.cs 48


public AppImpl()
{
  ....
  // load oodle
  var settingsManager = Locator.Current.GetService<ISettingsManager>();
  if (   settingsManager.IsHealthy()
      && !Oodle.Load(settingsManager?.GetRED4OodleDll()))
  {
    throw new FileNotFoundException($"{Core.Constants.Oodle} not found.");
  }
}

Unity C# reference source code

V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'package' object. PackageSample.cs 102


internal static IEnumerable<Sample> FindByPackage(PackageInfo package, ....)
{
  if (string.IsNullOrEmpty(package?.upmReserved) &&
      string.IsNullOrEmpty(package.resolvedPath))
  {
    return Enumerable.Empty<Sample>();
  }
  try
  {
    IEnumerable<IDictionary<string, object>> samples = null;
    var upmReserved = upmCache.ParseUpmReserved(package);
    if (upmReserved != null)
        samples = upmReserved.GetList<....>("samples");
    ....
  }
  ....
}