dotnet/roslyn

[NotNull] annotations are ignored for Nullable<T> fields/properties during nullable members' initialization checks

开放

#51,366 创建于 2021年2月20日

 (1 条评论) (0 个反应) (0 位负责人)C# (4,257 个派生)batch import
Area-CompilersBugFeature - Nullable Reference Typeshelp wanted

仓库指标

星标
 (20,414 个星标)
PR 合并指标
 (平均合并 6天 17小时) (30 天内合并 256 个 PR)

描述

Version Used:

Branch master (9 Feb 2021)
Latest commit 2d3ffe0 by msftbot[bot]:
Merge pull request #49990 from ryzngard/feature/namespace_analyzer

Add sync namespace analyzer

Steps to Reproduce:

Compile and run the following code

#nullable enable
using System.Diagnostics.CodeAnalysis;
public class C1
{
    [NotNull, DisallowNull] public int? Prop { get; set; }
    
    static void Main()
    {
        new C1().Prop.Value.ToString();
    }
}

Expected Behavior: CS8618: Non-nullable property 'Prop' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

Actual Behavior: No warnings at all. The program crashes with an InvalidOperationException: Nullable object must have a value.

Notes Note that Roslyn correctly reports warnings for fields and properties of reference and unconstrained generic types annotated with the [NotNull] attribute but fails to do so for Nullable<T>.

using System.Diagnostics.CodeAnalysis;
public class C1
{
    [NotNull] public string? x; // CS8618
    [NotNull] public int? y; // no warnings
}

public class C2
{
    [NotNull] public string? x;
    [NotNull] public int? y;
    
    public C2() { } // CS8618 reported for 'x' but not for 'y'
}

The same with properties instead of fields.

It looks like this check in NullableWalker shouldn't ignore Nullable<T>: https://github.com/dotnet/roslyn/blob/3ee6a8fea776de589329d6298df0dd80109bea3b/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs#L554

贡献者指南