Which is faster if else or ? :

Which is faster in c# either

int a = 10;
bool _IsEven;
if(a%2 == 0)
{
   _IsEven = true;
}
else
{
   _IsEven = false;
}

Or

int a = 10;
bool _IsEven = a%2 == 0 ? true : false;

UPDATE

I know here I can optimize my code just writing

bool _IsEven = a%2 == 0;

But my question is not about code optimization rather it is regarding about performance of these two statements???

Can you please help me to improve my coding knowledge?

Jon Skeet
people
quotationmark

Well your second code wouldn't even compile. But you could just write:

bool isEven = a % 2 == 0;

or

bool isEven = (a & 1) == 0;

Why use either the conditional operator or an if statement?

In general, when you have something like:

if (condition)
{
    x = true;
}
else
{
    x = false;
}

or

x = condition ? true : false;

you can just write:

x = condition;

I wouldn't be surprised to see the C# compiler optimize this anyway, but I wouldn't be as concerned with the performance as the readability.

people

See more on this question at Stackoverflow