Question

Possible Duplicates:
Benefits of using the conditional ?: (ternary) operator
Is the conditional operator slow?

Hi all,

I've got a pretty simple question regarding the different if/else statements.

Apart from writing less code, are there any other benefits for using the conditional operator as opposed to the full if/else statement?

Is there a performance increase, less compiled code, or anything else that would benefit me when using it?

Appreciate your help

Marko

Was it helpful?

Solution

Don't focus on writing less code... focus on the code you end up with being more readable.

Sometimes an if statement will be more readable. Sometimes the conditional operator will be more readable. I like the conditional operator in cases where it makes sense, in terms of different ways of calculating one logical value (e.g. a discount, based on the age of a customer). I don't like using it in convoluted ways though - there's nothing wrong with using a full if/else where it makes sense.

It's worth remembering the null-coalescing operator too... so instead of:

string shipTo = customer.ShippingAddress != null 
              ? customer.ShippingAddress : customer.BillingAddress;

you can use

string shipTo = customer.ShippingAddress ?? customer.BillingAddress;

Again, it's only useful in certain situations - but in those cases it's really handy.

OTHER TIPS

Apart from writing less code, are there any other benefits for using the Ternary operator as opposed to the full if/else statement?

Better readability, in some cases... I think that's all.

Is there a performance increase, less compiled code, or anyhing else that would benefit me when using it?

No, nothing significant. I think it will usually compile to the same IL anyway...

So eventually, you should only base your choice on readability. When it's more readable to write a full if/else, do it. If it's a very simple ternary expression that is easy to read, go for it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top