Non-nullable variables must be initializedDRT-W1542
The analyzer produces this diagnostic when a static field or top-level
variable has a type that's non-nullable and doesn't have an initializer.
Fields and variables that don't have an initializer are normally
initialized to null
, but the type of the field or variable doesn't allow
it to be set to null
, so an explicit initializer must be provided.
Examples
The following code produces this diagnostic because the field f
can't be
initialized to null
:
class C {
static int f;
}
Similarly, the following code produces this diagnostic because the
top-level variable v
can't be initialized to null
:
int v;
Common fixes
If the field or variable can't be initialized to null
, then add an
initializer that sets it to a non-null value:
class C {
static int f = 0;
}
If the field or variable should be initialized to null
, then change the
type to be nullable:
int? v;
If the field or variable can't be initialized in the declaration but will
always be initialized before it's referenced, then mark it as being late
:
class C {
static late int f;
}