Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize non-null properties using a method instead of constructor

Tags:

c#

null

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:

  1. Make the field nullable. However this means that everywhere where I try to access the field, I have to do a null-check
  2. As seen in the code sample, mark all fields that are initialized in 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

like image 208
Sander van 't Einde Avatar asked Dec 07 '25 07:12

Sander van 't Einde


1 Answers

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:

  1. If possible you could call the default constructor for your references (if any) like: private MyClass _reference = new MyClass(); (make sure that the reference does have a default constructor)
  2. You can use the # nullable disable above the reference property (this can still cause issues if the property is somehow null).
  3. Finally the null!

In conclusion there is no way to avoid null's if a reference is not instantiated at this point in time.

like image 172
GoldenWRaft Avatar answered Dec 08 '25 21:12

GoldenWRaft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!