with init keyword the property value can only be changed in constructor or initilize block.
if you use the default constructor
var s = new SomeClass ();
s.SomeProperty = "A value";//Compiler error CS8852 Init-only property or indexer "SomeClass.SomeProperty" can only be assigned in an object initializer, or on "this" or "base" in an instance constructor or an "init" accessor.
The property SomeProperty was initialized with null, but is not nullable reference type. the compiler is reporting a possible future runtime error. Warning CS8618 Non-nullable property "SomeProperty" must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
If there is no problem that this happens, the warning can be removed with the following
1. Use null forgiving operator
public class SomeClass
{
public string SomeProperty { get; init; } = null!;// indicating null value is a correct not null value.
}
When you try to access and use the SomeProperty value, you need to check nullability to avoid a null reference exception even though the type indicates that it is non-nullable. This is irritating.
if(s.SomeProperty==null) //OK
{
//DO SOME STUFF
}
var length = s.SomeProperty?.Length ?? 0; //OK
var length2 = s.SomeProperty;//NullReferenceException
2. Assigning/Initialize a valid value for property
public class SomeClass
{
public string SomeProperty { get; init; } = "My initial value";
}
you can invoke default constructor without initialze the property
var s = new SomeClass (); //Some property is "My initial value"
or invoke constructor with initialization block
var s = new SomeClass()
{
SomeProperty = "My new intial value"
};
var length = s.SomeProperty.Length; //NO exception / No problem
3. Create constructor with parameter, the default constructor is avoided.
Errors/Warnings only appear in the caller code.
public class SomeClass
{
public string SomeProperty { get; init; } //ALL OK. CS8618 dissapeared / No Warning.
public SomeClass(string someProperty)
{
SomeProperty = someProperty;
}
}
var s = new SomeClass(); //CS7036 ERROR.
var s2 = new SomeClass() //CS7036 ERROR.
{
SomeProperty = "My new intial value"
};
var s3 = new SomeClass("My new initial value"); //OK. No Warning
var s4 = new SomeClass("My new initial value") //OK. No Warning.
{
SomeProperty = "My other new intial value"
};
s4.SomeProperty = "A value"; //CS8852 ERROR. SomeProperty is enabled to only be initialized in constructor or intialize block.