Understanding why I'm still getting CS8618 Error In Constructor
Asked Answered
U

1

7

I'm getting to grips with the nullable change, but I've hit something that's giving CS8618 (Nullable field must contain non-null) but I don't think it should be.

Basically I have a private field, and my constructor calls an 'init/setup etc' method, the method does set the private field, but it's not happy.

i.e.

    public class Test
    {
        private object bob;

        public Test()
        {
            Init();
        }

        private void Init()
        {
            bob = new object();
        }
    }

The compiler highlights the constructor as being in error. Can I tell it somehow that Init() does what it wants? or is there something I'm missing that means that Init() might not be called in some situations which would make the warning valid?

I've tried a few ! at the end in places, but that doesn't seem to be it. If I move the code from Init() into the constructor the error does go away in this trivial example and the one in my code.

Uncrowned answered 23/5, 2022 at 10:28 Comment(3)
You must set the value in the constructor.Minorite
Add [MemberNotNull(nameof(bob))] to Init and Bob's your non-nullable uncle. Static analysis is not yet clever enough to figure out such things on its own.Engedus
For more details on MemberNotNullFalito
U
4

As per @Jeroen Mostert's comment, the solution is to add an attribute MemberNotNull to the child method, like so:

    public class Test
    {
        private object bob;

        public Test()
        {
            Init();
        }

        [MemberNotNull(nameof(bob))]
        private void Init()
        {
            bob = new object();
        }
    }

Note that future versions of C# may make this unnecessary.

Uncrowned answered 24/5, 2022 at 10:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.