[Solved] Return a String instead of an Integer


A better way to achieve what you’re trying to do overall would be to use an exception. Consider if we wrote AddNumbers as such:

public static int AddNumbers(int number1, int number2)
{
    int result = number1 + number2;
    if(result <= 10)
    {
        throw new Exception("Should be more than 10");
    }
    return result;
}

and our main logic as:

    try
    {
        int result = AddNumbers(3, 3);
    }catch(Exception e)
    {
        Console.WriteLine(e.Message); // must've been > 10
        return; 
    }

The way that this works is, when AddNumbers encounters behavior that is not expected or allowable, it will throw an Exception. When we call AddNumbers, now, we must do it in a try-catch block in order to catch this Exception, if it gets thrown. This approach is cleaner and less convoluted than using a Tuple, which is essentially reinventing the wheel in this scenario.

So, if our numbers add to less than 10, AddNumbers will throw an exception, which is then caught in our main logic and logged to the console, printing “Should be more than 10”.

Another option would be to simply change your main logic to be:

    int result = AddNumbers(x, 5);

    if(result > 10)
    {
        Console.WriteLine(result);
    }
    else
    {
        Console.WriteLine("You should have given me more than 5!");
    }

This has the advantage of being much simpler, but the disadvantage that we must remember to include this if statement every time we use AddNumbers. The Exception route is better design if we want to add more checks, for instance if you wanted to also require that the result be less than 30, divisible by 2, etc, you can just keep adding new thrown exceptions. However, if you only need to check if the result is greater than 10, it may be simpler overall to use this final option.

7

solved Return a String instead of an Integer