6

In c# can I do something like this in a shorthand?

 bool validName = true;
 if (validName)
 {
     name = "Daniel";
     surname = "Smith";
 }
 else
 {
     MessageBox.Show("Invalid name");
 }

I was just wondering if something similar to this would work, but in this exact scenario, I know you can assign values if I did name = validName ? "Daniel" : "Not valid", but I was just wondering if i can do the below?

     validName ? 
     {
         name = "Daniel";
         surname = "Smith";
     } 
     : 
     {
         MessageBox.Show("Invalid name");
     }
adminSoftDK
  • 2,012
  • 1
  • 21
  • 41
  • 12
    if/else is pretty short, and semantically clear. Even if there is a way to do that (which I doubt) I would recommend sticking with if/else. – BradleyDotNET Jul 30 '14 at 16:32
  • possible duplicate of [Method Call using Ternary Operator](http://stackoverflow.com/questions/5490095/method-call-using-ternary-operator) – Farhad Jabiyev Jul 30 '14 at 16:33
  • 5
    How is your second version "shorter"? It's the same number of lines, same structure, same number of operators. Is one or two keystrokes really so difficult? – David Jul 30 '14 at 16:35
  • 7
    this is one of those things you work on for 20 minutes and then realize you just wasted 20 minutes. – Jonesopolis Jul 30 '14 at 16:36
  • 8
    If the motivation here is simply to be clever, you might benefit from this quote... "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." --Brian Kernighan – David Jul 30 '14 at 16:39
  • Hi guys, I just wanted to find out if there is something like this. If else is very simple and i like it. I asked simply becuase i was wondering if something like this was possible. Becuase ive been using lots of if esle recently, and was wandering if thats ok, or wether i was doing some things wrong. As David said, i was trying to be a little clever too :) thanks for the comments ;) – adminSoftDK Jul 31 '14 at 08:15

5 Answers5

10

Abusing lambda syntax and type inference:

(validName
    ? (Action)
        (() =>
            {
                name = "Daniel";
                surname = "Smith";
            })
      : () =>
           {
                MessageBox.Show("Invalid name");
           })();

I know, not really an answer. If statement is way better: obviously this syntax is less readable and more importantly it has different runtime behaviour and could lead to unintended side effects because of potential closures created by the lambda expressions.

Syntax is a bit cryptic too. It first creates two Action objects then ?: operator chooses between them and at last the chosen result is executed:

var a1 = new Action(() => { /* if code block */ });
var a2 = new Action(() => { /* else code block */ });

Action resultingAction = test_variable ? a1 : a2;

resultingAction();

I put it together in one statement by executing the resulting action in place. To make it even briefer I cast the first lambda expression into an Action (instead of creating a new Action() explicitly) and taking advantage of type inference I left out the second cast.

mtmk
  • 6,176
  • 27
  • 32
  • 5
    I like it, avoids berating the OP and instead gives him a chance to be educated on lambda syntax in the future. – Christopher Bruce Jul 30 '14 at 16:54
  • 2
    This answer could use a bit more explanation about what it does and why it's not a good idea. – Colin DeClue Jul 30 '14 at 18:47
  • 1
    Thank you very much for the answer, this is actually more complicated than i thought it will be. I was just wondering because i saw those shorthands in a couple of places. But I'll stick with if else because of simplicity. Out of interest why the first lambda has Action and the second one has not? you you explain please? – adminSoftDK Jul 31 '14 at 08:12
  • @adminSoftDK: The first, second, or both subexpressions must have the cast to avoid a compiler error, "Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'". Lambda expressions don't have a speakable type. See also [Why can't an anonymous method be assigned to var?](http://stackoverflow.com/a/4966409/18192). – Brian Jul 31 '14 at 13:22
6

No.

The ternary operator (?:) must be, as a whole, an expression -- that is, something that can be assigned to something.

James Curran
  • 101,701
  • 37
  • 181
  • 258
  • 3
    While it is correct that the conditional operator must be a valid expression, it is not correct that such an expression cannot be used to perform the functional behavior described in the question. The behavior can be created through an expression, not just a statement. – Servy Jul 30 '14 at 16:42
  • @Servy : true, but the actions needed to turn the statements here into expressions would complete destroy the goal of making this a "shorthand" – James Curran Jul 30 '14 at 16:48
  • Sure, and if you said that it was possible, just not more convenient than using an `if` statement, the answer would be correct. When you say, "no", the answer is provably incorrect. – Servy Jul 30 '14 at 16:49
  • Your answer implies that the defining characteristic of an expression is that it can be on the right of an assignment. This is not the definition of an expression. There are eleven kinds of things that can be an expression in c# and most of them cannot appear on the right of an assignment. – Eric Lippert Jul 30 '14 at 18:29
  • 1
    @EricLippert: while technically true, it's a easy way to identify the types of expressions used by developers who aren't language designers. I.e, while most would know that `typeof int` is an expression (that can be assigned), few would recognize that means that the operand, `int` is also an expression, albeit one that cannot be assigned. However, that ignorance is unlikely to affect his code. – James Curran Jul 30 '14 at 19:01
6

Let's say you could do that. Why?

What is the motivation?

Fewer lines? not enough to make a difference. Performance? None, the compiler will handle things for you. Clarity? If/else is clearer and more easily understood by the majority of developers.

I am sure, if you worked hard enough, you could find a way to handle this (most likely a kludge), but I still cannot determine the why.

Gregory A Beamer
  • 16,870
  • 3
  • 25
  • 32
4

The conditional operator requires its second and third operands to be expressions that return a value (in addition to meeting some type restrictions) and not statements that do not resolve to a value. You have no value that you wish to return from either operation you are currently performing.

You could return some nonsensical value just for the sake of making the code compile, but at that point you're adding a ton more work than just using an if which is the correct semantic operator for your requirements, so while it is technically possible, it is not a good idea.

Servy
  • 202,030
  • 26
  • 332
  • 449
1
fullName = validName == true ? returnName(firstName)+" "+returnName(lastName) : validName == false ? invalidName("Invalid Name") : null


public string returnName(string name)
{
return name;
}

public string invalidName(string invalid)
{
MessageBox.Show(invalid);
return null;
}

As everyone else has probably said it's something you likely won't really want to do, but, it is possible :P

Christopher Bruce
  • 661
  • 3
  • 10
  • 24
  • This isn't assigning the relevant string literals to the appropriate name variables. – Servy Jul 30 '14 at 16:51
  • Of course it is. OP's code is assigning the names based on the assumption beforehand that the name is valid, and then assigning the values right after that. Clearly the names would be known before then, so just pass them in and return them immediately concatenated into fullName. Same with invalid. – Christopher Bruce Jul 30 '14 at 16:54
  • 1
    He's not constructing a `fullname` variable. He's assigning the values to two separate variables, `name` and `surname`. You are not assigning either such variable. – Servy Jul 30 '14 at 16:57