DEV Community

boomi1
boomi1

Posted on

Nested If vs. Ternary Operator in C#: When to Use What

Choosing between nested if and ternary is bit tricky. Let's see some real-time example to help choose the right one

using System;

public class HelloWorld
{
public static void Main(string[] args)
{
int age= 18;
bool hasTicket = true;
if(age >=18)
{
if(hasTicket)
{
Console.WriteLine("Allowed to enter");
}
else
{
Console.WriteLine("Please get the ticket");
}
}
else
{
Console.WriteLine("Age must be greater than or equal to 18");
}
}
}
Nested if is used in the above example.This can be achieved using ternary operator as well

Using Ternary Operator

using System;

public class HelloWorld
{
public static void Main(string[] args)
{
int age= 18;
bool hasTicket = true;
var result = age < 18 ? "Age must be greater than or equal to 18" :
(hasTicket ? "Allowed to enter" : "Please get the tickets");
Console.WriteLine(result);
}
}

Output for both nested and ternary
Allowed to enter

Use nested if

  • When the logic is complex Use ternary operator
  • For simple logic
  • While assigning or returning a value

Top comments (0)