dotnet/roslyn
View on GitHubIDE0270 - Cannot simplify for nullable implicit casts
Open
#72,052 opened on Feb 11, 2024
Area-CompilersBughelp wanted
Repository metrics
- Stars
- (20,414 stars)
- PR merge metrics
- (Avg merge 6d 17h) (256 merged PRs in 30d)
Description
Version Used: Version 17.9.0 Preview 4.0
Steps to Reproduce: I stumbled across this bug, I'm not sure what I'm doing is a good idea but reporting the bug nevertheless!
Given:
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
public interface IStatePersistence
{
Task<State> ResolveAsync(
string handle,
CancellationToken cancellationToken);
}
public enum StateType
{
None,
Auth,
}
public record State(
StateType Type,
byte[] Value)
{
// can't throw within implicit cast, so must return nullable:
public static implicit operator UserAuthenticationState?(
State state)
{
return JsonSerializer
.Deserialize<UserAuthenticationState>(
state.Value);
}
}
public record UserAuthenticationState(
string? blah);
public class UseCase
{
private readonly IStatePersistence _statePersistence;
public UseCase(
IStatePersistence statePersistence)
{
_statePersistence = statePersistence;
}
public async Task<UserAuthenticationState> Method(
string handle,
CancellationToken cancellationToken)
{
// Must be nullable here
UserAuthenticationState? state
= await _statePersistence
.ResolveAsync(
handle,
cancellationToken);
if (state == null)
{
throw new Exception();
}
return state;
}
}
Diagnostic Id: IDE0270
Expected Behaviour: IDE0270 error is not present
Actual Behaviour: IDE0270 is present, if I follow instructions it retains UserAuthenticationState? which is required for the implicit cast. Removal of the ? is not possible.