Thursday, December 4, 2014

C# When to use if else and when to use ternary operator



If you have any control flow, then use if else

int a = 1;
int b = 3;

// Use negated expression.
if (!(a == 1 && b == 2))
{
//Do some thing..
   Console.WriteLine(true);
}

// Use binary or version.
if (a != 1 || b != 2)
{//Do some thing..
   Console.WriteLine(true);
}


If you have any condition, based on condition if you want to assign any value then use ternary operator

Ex:
int input = Convert.ToInt32(Console.ReadLine());
string classify;
classify = (input < 0) ? "negative" : "positive";

No comments:

Loading...