Search code examples
c#conditional-operator

Method for displaying the largest of three numbers with the ? operator


I've been trying to define a method that should store the largest of three int numbers in a variable and then return that value.

Here's how I tried it:

public static int Max(int a, int b, int c)
{
    int iResult = 0;

    a > b && a > c ? iResult = a : b > a && b > c ? iResult = b : iResult = c;
    return(iResult);
}

Would be cool if someone could show me why the "?" operator doesn't work :)


Solution

  • ? : - ternary operator - gets 3 arguments and returns one result

      iResult = condition ? onTrue : onFalse;
    

    In our case we have to combine two ternary operators:

      iResult = condition1 ? onTrue1 
              : condition2 ? onTrue2
              : onFalse1and2;
    

    It can be (please, don't forget about formatting, let's keep the code being readable)

      iResult = a > b && a > c ? a
              : b > a && b > c ? b
              : c;
    

    Or we can get rid of iResult and put it compact as

      public static int Max(int a, int b, int c) =>
          a > b && a > c ? a
        : b > a && b > c ? b
        : c;