dotnet/roslyn

IDE0270 - Cannot simplify for nullable implicit casts

Open

#72.052 aperta il 11 feb 2024

Vedi su GitHub
 (3 commenti) (0 reazioni) (1 assegnatario)C# (4257 fork)batch import
Area-CompilersBughelp wanted

Metriche repository

Star
 (20.414 star)
Metriche merge PR
 (Merge medio 6g 17h) (256 PR mergiate in 30 g)

Descrizione

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!

sharplab.io

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.

image

Guida contributor