Home > database >  Non-nullable fields initialized inside a method called from the constructor
Non-nullable fields initialized inside a method called from the constructor

Time:10-29

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.

enter image description here

CodePudding user response:

Could you have PostInitializeComponent return the FlowPanel?

then

public PrintSettingsView(IServiceProvider serviceProvider, IPrintSettings printSettings)
{
    InitializeComponent();
   _flowPanel = PostInitializeComponent();
    // ...
}

If PostInitializeComponent does a bunch of work maybe extract out the part that builds FlowPanel and have that return it and assigned.

CodePudding user response:

what about defining them as nullable like:

FlowLayoutPanel? _flowPanel;

  • Related