Single Line If Statement in C#

Here is a standard if … then statement in C# followed by a single line example. Using a single line if statement will reduce the number of lines of code.

if (dayOfTheWeek == "Tuesday")
{
    lunchLocation = "Fuddruckers";
}
else
{
    lunchLocation = "Food Court";
}

And the same example as a single line if … then statement.

lunchLocation = (dayOfTheWeek == "Tuesday") ? "Fuddruckers" : "Food Court";
Tagged with:
Posted in C#
2 comments on “Single Line If Statement in C#
  1. Abbas says:

    is it necessary to add else, cant we just put the if condition. if yes than can you please reply me the syntax for the same…

  2. @Abbas – The SINGLE LINE method is expecting a colon followed by the else value. The default method does not require an ELSE.