简体   繁体   中英

C# readonly field is never assigned warning - can it be configured as an error

Given the following sample:

public class FooTest
{
    private readonly Foo foo;
        
    public FooTest()
    {
    }

    public void DoSomething()
    {
        var plop = foo.Bar();
    }
}

Which yields the following compilation warning:

[CS0649] Field 'FooTest.foo' is never assigned to, and will always have its default value null

We have an uninitialized field. For me, this is a developer error so I would like to see this as an error - not a warning .

So is there any way to make this an error? Either in the compilation or through analyzers or editorconfig ?

public class FooTest
{
    private readonly Foo foo;//this field is null so you need initialise it in constructor 
        
    public FooTest()
    {
         foo = new Foo();
    }

    public void DoSomething()
    {
        var plop = foo?.Bar();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM