Skip to content

Nullable Reference Types: CS8618 and/or CS8625 should be consistently reported for static fields/properties. #27014

@PathogenDavid

Description

@PathogenDavid

Version Used: 05/14/18 Nullable Reference Types Preview (csc reports 2.8.0.62830 (e595ee27)) with Visual Studio 15.7.1

Demonstration Code:

(For your convenience, here's all of the examples in this issue in one project: PathogenPlayground/InconsistentWarningsOnStaticFieldsAndProperties)

public class TestClass
{
    public string TestProperty { get; }
    public string testField;

    public static string TestStaticProperty { get; }
    public static string testStaticField;
}

Expected Behavior:

A CS8618 warning is reported for all four fields/properties.

Actual Behavior:

CS8618 is only reported for the instance field/property:

warning CS8618: Non-nullable property 'TestProperty' is uninitialized.
warning CS8618: Non-nullable field 'testField' is uninitialized.

Variations

While reporting this issue, I ended up finding out that adding null initializers and a static constructor changed the behavior as observed in the examples below:


Adding a static constructor does not change anything:

// (No warnings for TestStaticProperty or testStaticField)
public class TestClass
{
    public static string TestStaticProperty { get; }
    public static string testStaticField;

    static TestClass() { }
}

Adding null initializers does not change anything:

// (No warnings for TestStaticProperty or testStaticField)
public class TestClass
{
    public static string TestStaticProperty { get; } = null;
    public static string testStaticField = null;
}

Adding both null initializers and a static constructor does change things:

public class TestClass
{
    public static string TestStaticProperty { get; } = null; // warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter.
    public static string testStaticField = null; // warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter.

    static TestClass() { }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions