variable must be equal to a numerical value C# [closed]

all i need is to check if the two variables are equal to a numeric value,

The description of your problem and the description in the code are different. In the code you say you need to check to see if two variables are equal to any value in a particular range, not equal to a specific value. Let’s assume you mean the latter.

Is this the correct approach to take?

No. & has a particular meaning when applied to numbers, and it does not apply to decimals.

My advice for beginners is: when you are trying to represent a new concept, make a method that represents that concept. You can then refine that method as your skills improve.

When designing a method, think about: what goes in, and what comes out. We want a decision to be made, so a bool comes out. What goes in? The value we wish to test, and the range:

static bool IsInRange(decimal value, decimal low, decimal high)
{

OK, what are the conditions by which this thing can be false? If the value is lower than low, its not in the range, so say that:

  if (value < low)
    return false;

Similarly:

  if (value > high)
    return false;

We’ve now considered all the false cases, so the only remaining cases are always true:

  return true;
}

Now we have a tool that we can use.

if (IsInRange(operand1, 1m, 99999m) && IsInRange(operand2, 1m, 99999m)) ...

Are we done? No. Always ask yourself if there is a way to make the program more clear. There is:

const decimal low = 1m;
const decimal high = 99999m;
if (IsInRange(operand1, low, high) && IsInRange(operand2, low, high)) ...

Now if you decide to change the range, you only have to do it once. And now the meaning of 1m and 99999m is clear.

Leave a Comment