I have some non-nullable fields which I want to initialize inside a helper methods, called from a constructor, to reduce the clutter inside the constructor:
private FlowLayoutPanel _flowPanel;
private ComboBox _printersComboBox;
//...
public PrintSettingsView(IServiceProvider serviceProvider, IPrintSettings printSettings)
{
InitializeComponent();
PostInitializeComponent(); // this is where _flowPanel etc get initialized
// ...
}
How do I avoid warnings like Non-nullable field '_flowPanel' must contain a non-null value when exiting constructor. Consider declaring the field as nullable?
The best idea I've come up with so far:
public static void Assert([DoesNotReturnIf(false)] bool condition)
{
if (!condition) throw new InvalidOperationException();
}
public PrintSettingsView(IServiceProvider serviceProvider, IPrintSettings printSettings)
{
InitializeComponent();
PostInitializeComponent();
Assert(_flowPanel != null);
Assert(_printersComboBox != null);
//...
}
It's still getting messy when there's a lot of fields. Is there anything better than this?
It's a .NET 6 project, so I could use the latest and the greatest.

You have a few options:
[MemberNotNull] on the helper methods. This is a bit verbose but it should work. See https://stackoverflow.com/a/64958374/2855742.Another option is to declare the fields as:
private FlowLayoutPanel _flowPanel = null!;
private ComboBox _printersComboBox = null!;
This forces the compiler to consider these fields as initialized, and the ! suppresses warnings that the value is null yet the field is not nullable.
Note that adding the null assignment does not change the generated code. There is no run-time impact, only design-time.
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