dotnet/roslyn

IDE0270 - Cannot simplify for nullable implicit casts

Open

#72,052 opened on 2024年2月11日

GitHub で見る
 (3 comments) (0 reactions) (1 assignee)C# (4,257 forks)batch import
Area-CompilersBughelp wanted

Repository metrics

Stars
 (20,414 stars)
PR merge metrics
 (平均マージ 6d 17h) (30d で 256 merged PRs)

説明

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

コントリビューターガイド