In our architecture we have a method which is always invoked prior to invoking any other method. This method is intended for initializing references which are not available when the object is constructed.
Here is an example of such a class:
#nullable enable
public class MyClass
{
private MyReference _reference; // this shows a warning
public MyClass() { }
public void Activate()
{
_reference = new MyReference();
}
}
Right now I get warnings on the private field because it is not initialized in the constructor (which makes sense).
There are 2 solutions that I already tried, which are just not quite doing it for me:
Activate as = null!. This removes the error, however we do not enforce the actual initializing anywhere.My question is the following: Is there any attribute or method to make this example work, where I get both forced initialization (by way of compiler warnings) when initialization of my class' fields happen outside of the constructor
edit: Fix formatting of the question
I have looked into this a bit and most of the answers get the same conclusion that null! is the best option.
For instance you can have a look at this question by VivekDev:
Non-nullable property must contain a non-null value when exiting constructor. Consider declaring the property as nullable
Here there is a great answer from Slate:
The compiler is warning you that the default assignment of your string property (which is null) doesn't match its stated type (which is non-null string).
In turn there can be 3 solutions:
private MyClass _reference = new MyClass(); (make sure that the reference does have a default constructor)# nullable disable above the reference property (this can still cause issues if the property is somehow null).null!In conclusion there is no way to avoid null's if a reference is not instantiated at this point in time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With