In WinForms it is common that a common initialization function is initializing reference variables (for example)
class SomeClass : Form {
Button b;
SomeClass() {
InitializeComponents();
}
SomeClass(Container x) {
InitializeComponents();
}
void InitializeComponents() {
b = new Button();
}
}
As you can see b is always initialized to a non-null value. However, C# 8 will still complain that SomeClass() does not initialize non-nullable value b.
Of course I could mark b as nullable (Button? b) however, now I will get a warning on every usage of b, since nullability is not checked (it cannot be null...)
What is the best way to resolve this. Is there an attribute that can be used to flag InitializeComponent as being always called by constructor?
Please note, this is a very common pattern in WinForms (every component...)
Yuval
[MaybeNull]
. Do you know if any has been added that tells the compiler the field is always initialized? – Flexuous