Search code examples
c#.netvisual-studiosuppress-warnings

Annotate that a class method used in the constructor instantiates some class members


I have a class with constructors that share part of the initialization procedure. The IDE does not detect that initSomeExampleMembers() instantiates Map, and it therefore notifies me with "after the constructor execution Map should have a value, define it as nullable?"

I could locally suppress the warning or move the code back to the constructor and find a way to have them extend each other. But i was wondering: is there a way for me to annotate that that init() method is instantiating a specific member? Like an attribute for example

class ExampleClass {
    private ImmutableDictionary Map;

    private void initSomeExampleMembers() {
        //Fill Dictionary with 10 default instances of a class
    }
    ExampleClass() {
        initSomeExampleMembers();
    }
    ExampleClass(/*some params*/) {
        //"Example()"
        initSomeExampleMembers();
        //perform operations on Map items..
        //instantiate some more ExampleClass members..
    }
}

Solution

  • You can use MemberNotNullAttribute:

    [MemberNotNull(nameof(Map))]
    private void initSomeExampleMembers() 
    {
        //Fill Dictionary with 10 default instances of a class
    }
    

    Read more: