Martin Dzhonov Martin Dzhonov - 2 months ago 7
C# Question

Method that returns greater value of two numbers

So I have this code

static void Main(string[] args)
{
Console.Write("First Number = ");
int first = int.Parse(Console.ReadLine());

Console.Write("Second Number = ");
int second = int.Parse(Console.ReadLine());

Console.WriteLine("Greatest of two: " + GetMax(first, second));
}

public static int GetMax(int first, int second)
{
if (first > second)
{
return first;
}

else if (first < second)
{
return second;
}
else
{
// ??????
}
}


is there a way to make GetMax return a string with error message or something when first == second.

Answer
static void Main(string[] args)
{
    Console.Write("First Number = ");
    int first = int.Parse(Console.ReadLine());

    Console.Write("Second Number = ");
    int second = int.Parse(Console.ReadLine());

    Console.WriteLine("Greatest of two: " + GetMax(first, second));
}

public static int GetMax(int first, int second)
{
    if (first > second)
    {
        return first;
    }

    else if (first < second)
    {
        return second;
    }
    else
    {
        throw new Exception("Oh no! Don't do that! Don't do that!!!");
    }
}

but really I would simply do:

public static int GetMax(int first, int second)
{
    return first > second ? first : second;
}