Having a required init property which sets a backing field still gives a null warning.
The below code gives a warning:
Warning CS8618 Non-nullable field '_name' must contain a non-null value when exiting constructor. Consider declaring the field as nullable.
public class TestRequiredInit
{
private readonly string _name;
public required string Name
{
get => _name;
init => _name = value;
}
}
I don't see a way to create TestRequiredInit
without _name
being set to a non null value.
Is this a bug in MSBuild / VS, or am I missing something?
Update to prevent people from recommending using an auto property
I simplified the code above a bit for the purpose of asking a question. I want to be able to add initialization logic to the property initializer.
public class TestRequiredInit
{
private readonly string _name;
public required string Name
{
get => _name;
init
{
if (value.Length > 50)
{
throw new ArgumentException();
}
_name = value;
}
}
}