Narayanan Dayalan's Blog

Each problem that I solved became a rule which served afterwards to solve other problems


Leave a comment

Ternary Operator

Ternary operator is otherwise call as conditional operator, it is much easier to write and read the code at the later stage. It is similar to one we used in C++. I will explain the this with a simple example.

C#

private bool IsGreaterThan(int iNum1, int iNum2)
{
    if (iNum1 > iNum2)
    {
        return true;
    }
    else
    {
        return false;
    }
}

VB.NET

Private Function IsGreaterThan(ByVal iNum1 As Integer, ByVal iNum2 As Integer) As Boolean
    If iNum1 > iNum2 Then
    End If
    (
        Return True
    )
    else
    (
        Return False
    )
End Function

In the above code we have used if statement to check the condition, and it took 8 lines to check if iNum1 is greater than iNum2. Now lets see how we can make it simple by using Ternary Operator

C#

private bool IsGreaterThan(int iNum1, int iNum2)
{
    return (iNum1 > iNum2) ? true : false;
}

VB.NET

Private Function IsGreaterThan(ByVal iNum1 As Integer, ByVal iNum2 As Integer) As Boolean
    Return (iNum1 > iNum2) ? True : False
End Function

Now in the above sample, you can see the same implementation without if statement in just one line of code. Even this has some limitations, you can use this method every where. You can implement this when if statement is short. Wow sounds that simple right?