Post: [C#] Ternary Operators
05-31-2013, 04:41 AM #1
Master Ro
I make food
(adsbygoogle = window.adsbygoogle || []).push({}); I thought I would post a thread explaining what ternary operators really are.

Ternary operators are really just a bit of a shortcut.

For example, if I wanted to assign a value of "True" to a string that checked if an int was less than 10 and "False" to to a string that checked if the same int was greater than 10, I could write this.

    

int myInt = 5;
string isLessThan10 = null;

if( myInt < 10 )
isLessThan10 = "True";
else
isLessThan10 = "False";



This is how it would look using a ternary operator:

    

int myInt = 5;

string isLessThan10 = (myInt < 10) ? "True" : "False";



Let's step through this. The compiler first looks at the boolean value (myInt < 10) and evaluates it. If it's true, it reads the first expression (in this case "True"). If it's false, it reads the second expression (in this case "False").

Does it make a performance difference?

I don't think so, because the compiler is still evaluating two cases either way. It might make a slight difference, but nothing very noticeable. It's just an easier way of writing it :p.

Here's a sample program I made to further your understanding Winky Winky

You must login or register to view this content.

If you have any questions, feel free to reply on this thread.

Thanks,
Ro
Last edited by Master Ro ; 05-31-2013 at 04:43 AM.

The following 5 users say thank you to Master Ro for this useful post:

KCxFTW, Dan, Pichu,
05-31-2013, 04:48 AM #2
Dan
I'm a god.
Nice little tutorial, Ro! Hope to see more! Happy
06-01-2013, 06:38 AM #3
Pichu
RIP PICHU.
I always forget about using ternary operators lol.

Copyright © 2024, NextGenUpdate.
All Rights Reserved.

Gray NextGenUpdate Logo