6

I have a function with multiple if's (THIS IS NOT THE ACTUAL CODE)

if(n == 1)
   m = 1;
if(n == 2)
   m = 2;
if(n == 3)
   m = 3;

Instead of that I wanted to do make them all into ?: expression :

(n == 1) ? m = 1;

But it says that its expecting a ':'

I am familiar with the ?: expression from C++ where you can simply write:

(n == 1) ? m = 1 : 0;

But 0 doesn't take here. This is a ridiculous question and I couldn't even find an answer in google since it ignores '?:' as a word.

ANSWER : too bad the answer was in the comments. There is no way to "do nothing" in this expression and I should use if-else or switch. thanks.

user779444
  • 1,365
  • 4
  • 21
  • 38
  • Yes, it's hard to Google a question mark. This is called a ternary operator. – DOK Jan 21 '12 at 18:52
  • 8
    An "if" statement *executes a statement if a condition is met*. A conditional expression *chooses an expression to evaluate if a condition is met*, and in C# it *must do something with that expression*. (Unlike in C++, where the expression can be executed for its side effects.) You're mixing the two styles together in a strange way; don't do that. It is usually impossible, and when it is possible, it is very confusing. Use a switch, or an if-else; that is much more readable. – Eric Lippert Jan 21 '12 at 18:54
  • 3
    @DOK: It is called a *conditional* operator. It happens to be the only ternary operator in C#, so people sometimes call it "the ternary operator" because there is only one. But it is better to describe a thing based on its *purpose* than its *form*. – Eric Lippert Jan 21 '12 at 18:55
  • possible duplicate of [How does the ternary operator work?](http://stackoverflow.com/questions/463155/how-does-the-ternary-operator-work) – Grant Thomas Jan 21 '12 at 18:55
  • There are two questions here. The first is *how does the operator `?:` work in C#?* The second is *what's the best way to express the logic represented in this chain of `if` statements?* IMHO, the answer to the second question is not to use `?:`. – grossvogel Jan 21 '12 at 18:56
  • 1
    [Sample code](http://sscce.org/) should be representative as well as complete and concise. The given sample isn't a good representation. Consider picking a [meaningful username](http://tinyurl.com/so-hints). One advantage to this is others can use [at-replies](http://meta.stackexchange.com/questions/43019/how-do-comment-replies-work) and you'll get a notification that someone has addressed you in a comment. – outis Jan 21 '12 at 19:12

8 Answers8

14

It looks like you're looking for:

m = (n == 1) ? 1 : 0;

Which you could then cascade to:

m = (n == 1) ? 1 : (n == 2) ? 2 : (n == 3) ? 3 : 0;

An important (to me, anyway), aside:

Why are you asking this? If it's because you think that this form will be more efficient than a series of if statements, or a switch, don't. The C# compiler and the .net JIT compiler are really quite clever and they'll transform your code (hopefully!) into its most optimal form. Write your code so its as understandable by yourself, or the developer who has to maintain it after you as it can be. If the performance you get isn't acceptable, then try changing it around but measure to determine what works best (bearing in mind that newer compilers/.net frameworks could well change what happens).

Rob
  • 45,296
  • 24
  • 122
  • 150
  • Wow, I didn't realize you could chain them together. – DOK Jan 21 '12 at 18:54
  • 7
    @DOK - you can, doesn't mean it makes for anything other than horribly un-readable code though! ;=) – Rob Jan 21 '12 at 18:56
  • @Rob [It doesn't have to be](http://pastebin.com/0kHXD1Hd). Not sure if C# has `#define`, but that's what I do in C/C++. – Pubby Jan 21 '12 at 19:02
  • @CodeInChaos [It does.](http://msdn.microsoft.com/en-us/library/yt3yck0x(v=vs.71).aspx) But it can't be used for macros. – GameZelda Jan 21 '12 at 20:51
  • @ Pubby C# doesn't have macros, so you can't do this in C#. @GameZelda Thanks, my comment was a bit sloppy. – CodesInChaos Jan 21 '12 at 20:56
  • @Rob proper nesting is the solution to this ugly code. Blowing out a sequence of ifs like that can be just as unreadable, imho – JoeBrockhaus May 15 '14 at 21:41
2

looking for ternary operator in c# will give you relevant results.

an example usage would be

var m = n == 1 ? 1 : 0
flq
  • 22,247
  • 8
  • 55
  • 77
2

Maybe:

m = (n == 1) ? 1 : (n == 2) ? 2 : (n == 3) ? 3 : m;

or

m = n

Edit: Simplified:

variable2 = (variable1 == value) ?
             variable1 :
             variable2;
Gilad Naaman
  • 6,390
  • 15
  • 52
  • 82
1

You could write:

m = (n==1) ? 1 : m;

But IMO that's harder to read and uglier than the original code.

(n == 1) ? m = 1 : 0;

This isn't allowed because C# doesn't allow arbitrary expressions as a statement. Method calls and assignments are allowed, most other expressions aren't.

A statement is executed for its side-effects, an expression for its value. So it's only natural that the outermost part of a statement has a side effect. ?: never has a side-effect, so it's not allowed as a statement.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
1

You want this:

m = (n == 1) ? 1 : 0;

To nest them all it would look like this:

m = (n == 1) ? 1 : (n == 2) ? 2 : (n == 3) ? 3 : 0;

But as you can see, this is really a lot less easy to read and understand. It can help to add extra parenthesis, but I think you're better off using an if-else tree.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
1
m = (n == 1) ? 1 : m

Means

M equals 1 if n == 1, else m

FYI the ? is called the Ternery operator. Find usage on MSDN

Best regards,

Dr. Andrew Burnett-Thompson
  • 20,980
  • 8
  • 88
  • 178
0

Try this :

m = (n == 1) ? 1 : 0;
Saber Amani
  • 6,409
  • 12
  • 53
  • 88
0

This is not a problem to be solved with a ternary if/else operator - it is clearly an ideal candidate for a switch statement (and using a switch is likely to be much more efficient than using a sequence of ternary operators)

If you wish to transliterate an if statement into ?:, then it's quite simple:

if ({condition}) {then-code}; else {else-code};

becomes

{condition} ? {then-code} : {else-code};

The only restriction is that the then/else code is a single statement.

The primary benefit of ?: (with modern compilers) is that it can be embedded within a statement to significantly compress the source code - sometimes this can aid readability, and sometimes it just serves to obfuscate the meaning of the code - use it with care.

Jason Williams
  • 56,972
  • 11
  • 108
  • 137