Search code examples
c#null

Initialize non-null properties using a method instead of constructor


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


Solution

  • For your specific use case, we can hack something together with the MemberNotNull attribute.

    I say hack cause it's meant to decorate methods that are called from the ctor. Conceptually, however, it makes sense here, given Activate is always invoked prior to invoking any other method.

    ctor_warning

    This does mean we will have to suppress the non-null value when exiting constructor warning. Once we do that and we forget to set the reference inside Activate, the only remaining compiler warning is the one you're after.

    method_warning

    It should do the trick with your architecture as you can decorate the Activate method for each implementing class, for its own fields.