Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reporting "field is uninitialized" for constructor that throws an exception #25529

Closed
cston opened this issue Mar 16, 2018 · 4 comments
Closed
Assignees
Milestone

Comments

@cston
Copy link
Member

cston commented Mar 16, 2018

Reports: (5,14): warning CS8618: Non-nullable field '_f' is uninitialized.

using System;
class C
{
    private object _f;
    internal C()
    {
        throw new NotImplementedException();
    }
}
@gafter
Copy link
Member

gafter commented Mar 16, 2018

In unreachable code every variable is definitely not null.

@AlexanderTaeschner
Copy link

Yes, but in this case, the call to this default constructor will not create a class with an uninitialized field either, since the constructor call will fail! The use case would be a class with a second constructor, e.g. public C(object f) => _f = f; which guarantees the initialization of the internal field.

@gafter
Copy link
Member

gafter commented Mar 16, 2018

@AlexanderTaeschner Agreed. That is why the rule I stated works for this case (the end of the constructor is not reachable).

@jcouv
Copy link
Member

jcouv commented Mar 14, 2019

This issue still exists in recent 16.1 branch:

        [Fact]
        public void Test()
        {
            var comp = CreateCompilation(@"
using System;
class C
{
    private object _f;
    internal C()
    {
        throw new NotImplementedException();
    }
}", options: WithNonNullTypesTrue());
            comp.VerifyDiagnostics(
                // (5,20): warning CS0169: The field 'C._f' is never used
                //     private object _f;
                Diagnostic(ErrorCode.WRN_UnreferencedField, "_f").WithArguments("C._f").WithLocation(5, 20),
                // (6,14): warning CS8618: Non-nullable field '_f' is uninitialized.
                //     internal C()
                Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "_f").WithLocation(6, 14)
                );
        }

agocke added a commit that referenced this issue Apr 2, 2019
)

If the end of a constructor is unreachable we shouldn't warn about
fields which are uninitialized at the end.

Fixes #25529
@jcouv jcouv modified the milestones: 16.1.P1, 16.1.P2 Apr 2, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants