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.