Thursday 22 March 2012

C# Ternary Operator

Well I read about ternary operators the other day and wondered when I was going to get to use them.

The c# ternary operators replace the need for the if else statement. It's doing the same thing but it's certainly less typing involved and more condensed to look at.


        private static int GetPageIndex(int startRowIndex, int maximumRows)
        {
            //the old way I would have done things
            if (maximumRows <= 0)
            {
                return 0;
            }
            else
            {
                return (int)Math.Floor((double)startRowIndex / (double)maximumRows);
            }

            //and now using the ternary operator
            return (maximumRows <= 0)
                ? 0
                : (int)Math.Floor((double)startRowIndex / (double)maximumRows)
                ;
           
            //or you could just write it like this
            return (maximumRows <= 0) ? 0 : (int)Math.Floor((double)startRowIndex / (double)maximumRows);
        }

The question mark "?" is the if part of the if...else statement and the colon/double stop ":" is the else part of the if...else statement.

What this is saying is that if maximumRows is less than or equal to 0 then "?" return a value of 0 else ":" return the result of the calculation.

No comments:

Post a Comment