-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Closed
Labels
area-Extensions-DependencyInjectionin-prThere is an active PR which will close this issue when it is mergedThere is an active PR which will close this issue when it is merged
Description
Description
ServiceDescriptor.ServiceKey is typed as object? with nullable reference types enabled.
The static analyzer then cannot take into account the result of ServiceDescriptor.IsKeyedService and even if the service is known to be a keyed service, believes ServiceKey may still be null.
Even though IsKeyedService is implemented as
/// <summary>
/// Indicates whether the service is a keyed service.
/// </summary>
public bool IsKeyedService => ServiceKey != null;Reproduction Steps
#nullable enable
public void Example(ServiceDescriptor descriptor)
{
if (descriptor.IsKeyedService) {
object serviceKey = descriptor.ServiceKey; // <-- complains about potential nullness
}
}Expected behavior
Would expect no complaints about potential nullness.
Actual behavior
Got complaints about nullness.
Regression?
No response
Known Workarounds
Use the 'null-forgiving' operator (!) to discard potential nullness. E.g.
#nullable enable
public void Example(ServiceDescriptor descriptor)
{
if (descriptor.IsKeyedService) {
object serviceKey = descriptor.ServiceKey!; // <-- no longer complains about potential nullness
}
}Configuration
.NET version: .NET 10
Other information
The problem lies in a missing [MemberNotNullWhen] annotation.
The following should fix it:
/// <summary>
/// Indicates whether the service is a keyed service.
/// </summary>
[MemberNotNullWhen(returnValue: true, nameof(ServiceKey)]
public bool IsKeyedService => ServiceKey != null;Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
area-Extensions-DependencyInjectionin-prThere is an active PR which will close this issue when it is mergedThere is an active PR which will close this issue when it is merged