Dovahkiin Dovahkiin - 1 month ago 7
C# Question

C# - Finding maximum of 3 numbers using if / else statements

I'm completely new to C# - just trying out some simple stuff.
I want to find the maximum of three numbers, using if/else statements. I tried writing this method:

public int Maximum(int num1, int num2, int num3)
{
if (num2 < num1 > num3)
{
return num1;
}

else if (num1 < num2 > num3)
{
return num2;
}

else if (num1 < num3 > num2)
{
return num3;
}
}


but I've gotten a bit confused.

Q1 - By saying "int Maximum", do I still need to declare each parameter as being an int (or the same the other way round)? Or does everything need its data type declared?

Q2 - Keeps telling me that "Operator '>' cannot be applied to operands of type bool and int"? I'm confused as to what I should do here. Have I done something wrong or is there an alternative?

Thanks for any help.

Answer

Regarding Q1

C# is a strongly typed language. This means that you must explicitly tell the compiler the types of your parameters, variables, members, and even your methods return value.

This is similar to other strongly typed languages, such as Java or C++.

P.S.: Newest C# keywords (such as var or dynamic) try to move C# from a strongly typed environment to an hybrid one.

Regarding Q2

num < num2 > num3 is not a valid condition expression.

num < num2 yields a bool, so the following expression num < num2 > num3 would be equivalent to bool > num3, which is invalid, since you can't compare a bool and an int like this.

What you're looking for is the Conditional AND (&&) operator:

if (num < num2 && num2 > num3)
{
    return num2;
}

Alternatively, you can also use nested if statements to achieve the same behaviour:

if (num < num2)
{
    if (num2 > num3)
    {
        return num2;
    }
}

Regarding your code

The code you have provided has another problem.

What would happen if none of the three conditions are met? What would the method return?

Of course, you know that it's not possible for the three conditions to never be met, but the compiler doesn't know this.

You have to either return a dummy value, or remove your last else if:

public int Maximum(int num1, int num2, int num3)
{
    if (num2 < num1 && num1 > num3)
    {
        return num1;
    }

    else if (num1 < num2 && num2 > num3)
    {
        return num2;
    }

    // If we reached this point, we know that num3 is the biggest of them all
    else
    {
        return num3;
    }
}