Wich is Better in C#:
if(a < b)
{
c = 1;
}
else
{
c = 0;
}
or
c = a < b ? 1 : 0;
Wich is Better in C#:
if(a < b)
{
c = 1;
}
else
{
c = 0;
}
or
c = a < b ? 1 : 0;
Well, I generally prefer using the top example myself, simply because it is easier to read at a glance. Which makes code maintenance easier, and it makes it easier for others to follow your code. But honestly, they are both just fine and it is mostly personal preference.
thnx, i was looking for wich one is less expencive to use in memory usage, but if they are the same, ill use the first one. like you said, is easy to read.
They compile to the same IL code, so they are identical. First one is easier to step through when debugging, second one is more concise. If the logic is tricky I will typically do the full if-else until I know it works correctly and then convert to the ternary operator afterwards.
I’m not 100% sure, but I would think that most compilers would compile each down to the same byte code. Even if they don’t, I would imagine any benefit you get from the more “efficient” one would be VERY inconsequential. In my experience, the benefits of readability and maintainability far out weigh the benefits from micro optimizations like this.
If I only need to do a simple conditional assignment, I usually go with the ternary operator. They make for uglier code, but it’s far more compact, and if the statement is simple enough, it doesn’t really hurt readability much IMO.
As far as performance goes, I don’t think there is any difference at all, the compiler will most likely generate the same code for both cases.
Another thing I sometimes like to do, which also makes for compact code and terrible reading, is when assigning a boolean value based on a condition, which would usually be done like this:
if (something != somethingElse )
myBool = true;
else
myBool = false;
I do this:
myBool = something != somethingElse;
This example is simple enough that the latter statement is just more convenient. But I have been guilty of doing some pretty much unreadable expressions in that form… Sometimes combining boolean logic operators with ternaries as well, and ending up with a nice twisted mass of unintelligible code.
Cheers
Ternary Operators are fine - as long as they are used in a clear and understandable fashion.
‘Writing Solid Code’ [Microsoft press] gives an example of bad usage.
The goal is to create a function that handles two cycles:
The solution was simple:
int CycleCheckBox (int i)
{
return ((i<=1) ? (i==1?0:1) : (i==4)?2:(i++));
}
Except no one can read that. So we try to expand it:
int CycleCheckBox(int i)
{
if (i <= 1)
{
if (i!=0) i = 0;
else i = 1;
}
else
{
if (i == 4) i = 2;
else i++;
}
return i;
}
And we notice there’s a ton of if statements. Suddenly we realize the following:
int CycleCheckBox(int i)
{
if (i == 1) return 0;
if (i == 4) return 2;
return ++i;
}
Now, which is easier to read? Which is faster?
So yeah, be careful.