1

I have a class that is like

    class Operation
    {
        private int? opA = null;
        private int? opB = null;
        private Func<int>? opFunc = null;

        public void SetOperandA(int value)
            => opA = value;
        public void SetOperandB(int value)
            => opB = value;

        public void SetAdd()
            => SetOperator(() => (int)opA + (int)opB);
        public void SetSubtract()
            => SetOperator(() => (int)opA - (int)opB);

        public void SetOperator(Func<int> op)
        {
            if (opA is null || opB is null)
                throw new Exception("Both operands must be set first!");
            opFunc = op;
        }

        public int Evaluate()
        {
            if (opFunc is null)
                throw new Exception("Operator must be set first!");
            return opFunc();
        }
    }

The issue is that in the SetAdd() function, VS complains about the line SetOperator(() => (int)opA + (int)opB); saying that opA and opB may be null, even though they should never both be null by how SetOperator() works.

I'm trying to tell VS that it's as if I'm doing

        public void SetMultiply()
        {
            if (opA is null || opB is null)
                throw new Exception("Both operands must be set first!");

            opFunc = () => (int)opA * (int)opB;
        }

where VS is able to deduce that at the line opFunc = () => (int)opA * (int)opB;, both opA and opB aren't null and there are no potential issues.

I've tried adding

        [MemberNotNull(nameof(opA))]
        [MemberNotNull(nameof(opB))]
        private void SetOperator(Func<int> op) { /* ... */ }

but this doesn't affect what I'm after.

user137794
  • 1,636
  • 2
  • 10
  • 11

2 Answers2

4

You can use null-forgiving operator (!):

public void SetAdd()
        => SetOperator(() => (int)opA! + (int)opB!);
public void SetSubtract()
        => SetOperator(() => (int)opA! - (int)opB!);

Which is basically the same as "shut up, I know better".

Or use the pragma - #nullable:

#nullable disable
    public void SetAdd()
        => SetOperator(() => (int)opA + (int)opB);
    public void SetSubtract()
        => SetOperator(() => (int)opA - (int)opB);
#nullable restore
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
0

You can use the null-forgiving operator (!), which tells the compiler that you're absolutely certain that the value won't be null. You can do this by adding ! after the nullable variable.

Try changing the line:

setoperator(() => (int)opa + (int)opb);

to:

setoperator(() => (int)opa! + (int)opb!);

This should resolve the issue in Visual Studio and allow you to compile the code.