Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid CS8618 warning when local member is instantiated via different method called within constructor

This question relates to the nullable / non-nullable reference types that were added in C# 8.0

If I have the Nullable property within my project set to 'Enable', and I have a class where a field is instantiated during the constructor, but via a call to a separate method - how can I avoid the following warning?

CS8618 'Non-nullable field must contain a non-null value when exiting constructor. Consider declaring the field as nullable.'

Is there something fundamentally wrong about setting a nullable members value this way?

Example:

public class Foo
{
    public Foo()
    {
        //Do some other constructor stuff
        InitialiseBar();
    }

    private void InitialiseBar()
    {
        _bar = new Bar();
        //Do some initial stuff with _bar
    }

    private Bar? _bar;
}
like image 698
GraySquid Avatar asked Jan 22 '26 16:01

GraySquid


1 Answers

You can use the MemberNotNull attribute for this. This tells the compiler that the marked function ensures the member is not null.

[MemberNotNull(nameof(_bar))]
private void InitialiseBar()
{
    _bar = new Bar();
    //Do some initial stuff with _bar
}

dotnetfiddle

like image 82
Charlieface Avatar answered Jan 25 '26 13:01

Charlieface



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!