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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With