C# ? : Operator condition

4/1/2014·1 min read

use (?:) depend on how you use, some time make your coding more productive and readable.

1. simple codition

C# -- use if elsepublic string CheckCondition(int year)
{
if (year < 2012)
{
return "less than 2012.";
}
else
{
return "greater than 2012.";
}
}
C# -- use ? : conditionpublic string CheckCondition(int year)
{
return (year < 2012) ? "less than 2012." : "greater than 2012.";
}

2. complex case

C# -- use if elsepublic string CheckCondition(int year)
{
if (year < 2012)
{
if (year > 2000 && year < 2012)
{
return "between 2000 and 2012.";
}
else
{
return "less then 2000.";
}
}
else
{
if (year == 2025)
{
return "this's 2025.";
}
else
{
return "greater than 202012 and not 2025.";
}
}
}

to me, it's less line to use ?: condition, but it's harder to read.

C# -- use ? : condition [t ? a ? b ? c : e ? f : j]public string CheckCondition(int year)
{
return (year < 2012) ? (year > 2000 && year < 2012 ? "between 2000 and 2012.""less then 2000.") : (year == 2025 ? "this's 2025." : "greater than 202012 and not 2025.");
}

Conclustion

C# ?: condition is good to use simple condition, less code. But it's questionable if use for very complext condition since it's hard to read and debug.

Operators ?: also can't be overloaded. So, if you want to try something like How to OverLoading Operator.This. Which you can't do it for (?:).