views:

214

answers:

2

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

+3  A: 

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.

Jon Skeet
Thank you - that's all I needed to know. I've been reading through some code and have found that some developers over-complicate code by using the ternary operator in places where they probably shouldn't have. Will accept in 8 minutes!
Marko
@Marko: Quick note of pedantry, the *name* of the operator is the conditional operator. It's a ternary operator because it has three operands, but that's just a property of the operator rather than a description of it.
Jon Skeet
Awesome - thanks @Jon. I'm still waiting for your book to arrive, no doubt I'll have more questions after I've read it! Thanks!
Marko
+1  A: 

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.

Thomas Levesque
Perfect - thank you!
Marko