Home > Enterprise >  C# checking what condition was met in if statement with multiple conditions
C# checking what condition was met in if statement with multiple conditions

Time:12-22

I am checking for an error exception if some inputs are greater than 7 or smaller than 0:

if (number1 > 7 || number1 < 0 || number2 > 7 || number2 < 0){
  throw new Exception("Invalid position <pos>");
}
catch (Exception e){
  Console.Write(e)
}

how can I print what number was the error? E.g: number1 is 10 but number2 is 3, i want to print "Invalid position <10>"

CodePudding user response:

I want to know if it's possible to check what condition is met in the if statement without using many if/elseif statements.

There is no such way, you'd have to split your if.

if (number1 > 7 || number1 < 0 ){
  throw new Exception($"Invalid position <{number1}>");
}
elseif(number2 > 7 || number2 < 0) {
  throw new Exception($"Invalid position <{number2}>");
}
catch (Exception e){
  Console.Write(e)
}

CodePudding user response:

The easiest thing to do would be to split this if statement up into a func:

Func<int,int,int,bool> InRange= (number,low,high) =>
{
  if(number>high || number<low)
      return false;
  return true;
}

if(!InRange(number1,0,7))
  throw new Exception($"Invalid position <{number1}>");
if(!InRange(number2,0,7))
  throw new Exception($"Invalid position <{number2}>");

Really though in cases like theses your numbers should be in some sort of list so it would be more like:

foreach (var number in numbers)
  if(!InRange(number,0,7))
     throw new Exception($"Invalid position <{number}>");

Also you should not use hard coded number like 0 and 7. They should either be inputs or set to constants

CodePudding user response:

If number1 and number2 are arguments, you can just validate them separatedly:

// if number1 and number2 are input parameters, we just validate them: 
if (number1 < 0 || number1 > 7)
  throw new ArgumentOutOfRangeException(nameof(number1), "Invalid position <pos>");
if (number2 < 0 || number2 > 7)
  throw new ArgumentOutOfRangeException(nameof(number2), "Invalid position <pos>");

If number1 and number2 are some kind of settings, you can exploit the same idea:

// If number1 and number2 are local variables, we have some inner problems
// in the routine. That's why I vote for - InvalidOperationException -
// something when wrong
if (number1 < 0 || number1 > 7)
  throw new InvalidOperationException(
    $"Invalid position <pos>, {nameof(number1)} = {number1} is out of [0..7] range.");
if (number2 < 0 || number2 > 7)
  throw new InvalidOperationException(
    $"Invalid position <pos>, {nameof(number2)} = {number2} is out of [0..7] range.");

Please note, that throwing as well as catching (swallowing) Exception is often a bad practice: your code should deal with an easy case only when number1 or number2 are out of range and not with all possible exceptional situations.

If you want to write some warning and keep on doing, you can get rid of exception throwing at all:

if (number1 > 7 || number1 < 0)
  Console.Write($"Invalid position <pos>: {nameof(number1)} is out of range");
else if (number2 > 7 || number2 < 0)
  Console.Write($"Invalid position <pos>: {nameof(number2)} is out of range");
else {
  // Both number1 and number2 are valid
}

CodePudding user response:

A simple solution, with a single throw, contrary to the other solutions:

if (number1 > 7 || number1 < 0 || number2 > 7 || number2 < 0)
{
    var invalidNumbers = new List<string>();
    if(number1 > 7 || number1 < 0)
    {
        invalidNumbers.Add($"{number1}");
    }
    if (number2 > 7 || number2 < 0)
    {
        invalidNumbers.Add($"{number2}");
    }
    throw new Exception($"Invalid position {string.Join(", ",invalidNumbers)}");
}

If number1, or number2, or both number1 and number2 are wrong, you are notified via one unique exception.

If your condition is the same for every numbers, as you might imply:

if some inputs are greater than 7 or smaller than 0

you can generalize easily and have a more elegant code using Linq:

var number1 = 8;
var number2 = -1;

var numbers = new List<int>
{
    number1,
    number2
    // Add as many numbers as you wish.
};

var wrongNumbers = numbers
    .Where(n => n > 7 || n < 0) // The condition to apply to all numbers.
    .ToList();
    
if(wrongNumbers.Any())
{
    var wrongNumbersAsString = string.Join(", ", wrongNumbers
        .Select(n => $"{n}"));

    throw new Exception($"wrong numbers: {wrongNumbersAsString}");
}
  • Related