Examples of errors detected by the V3042 diagnostic
V3042. Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the same object.
PixiEditor
V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'command' object NativeMenu.cs 68
public static async void CommandChanged(AvaloniaPropertyChangedEventArgs e)
{
....
RelayCommand<object> wrapper = new RelayCommand<object>(parameter =>
{
if (!ShortcutController.ShortcutExecutionBlocked)
{
if ( command?.Shortcut != null
&& command.Shortcut.Gesture != null
&& command.Shortcut.Gesture.Key != Key.None
|| command.Shortcut.Gesture.KeyModifiers != KeyModifiers.None) // <=
{
ViewModelMain.Current.ShortcutController.KeyPressed(
false,
command.Shortcut.Key,
command.Shortcut.Modifiers);
}
else
{
if (iCommand.CanExecute(parameter))
{
iCommand.Execute(parameter);
}
}
}
....
});
....
}
Files
V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'context' object Files.App OpenClassicPropertiesAction.cs 40
public Task ExecuteAsync(object? parameter = null)
{
if (context.HasSelection && context?.SelectedItem?.ItemPath is not null)
ExecuteShellCommand(context.SelectedItem.ItemPath);
else if (context?.Folder?.ItemPath is not null)
ExecuteShellCommand(context.Folder.ItemPath);
return Task.CompletedTask;
}
QuantConnect Lean
V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'result' object. EulerSearchOptimizationStrategy.cs 73
public override void PushNewResults(OptimizationResult result)
{
....
if ( !ReferenceEquals(result, OptimizationResult.Initial)
&& string.IsNullOrEmpty(result?.JsonBacktestResult))
{
_runningParameterSet.Remove(result.ParameterSet);
return;
}
....
}
.NET 9
V3042 Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'root' object MemberObjectsExplorer.cs 109
private static async Task<JArray> GetRootHiddenChildren(...., JObject root)
{
var rootValue = root?["value"] ?? root["get"];
if (rootValue?["subtype"]?.Value<string>() == "null")
return new JArray();
....
}
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");
....
}
....
}
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.");
}
}
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);
}
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 'mergeExpandValue' object TabularDataQueryOptions.cs 282
internal bool AppendExpandQueryOptions(ExpandQueryOptions mergeExpandValue)
{
....
ExpandQueryOptions[mergeExpandValue.ExpandInfo.ExpandPath] =
mergeExpandValue?.Clone();
return true;
}
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];
}
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;
}
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,
};
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;
....
}
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;
....
}
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,
....
},
....
}
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
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(....); // <=
}
....
}
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) // <=
},
},
....
}
.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);
....
}
.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; // <=
....
}
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;
}