c# If else shorthand
Asked Answered
W

5

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");
     }
Wesla answered 30/7, 2014 at 16:31 Comment(6)
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.Graecoroman
possible duplicate of Method Call using Ternary OperatorHewie
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?Tableau
this is one of those things you work on for 20 minutes and then realize you just wasted 20 minutes.Boardinghouse
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 KernighanTableau
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 ;)Wesla
M
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.

Mccollough answered 30/7, 2014 at 16:54 Comment(4)
I like it, avoids berating the OP and instead gives him a chance to be educated on lambda syntax in the future.Gelderland
This answer could use a bit more explanation about what it does and why it's not a good idea.Unsaddle
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?Wesla
@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?.Versus
F
6

No.

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

Fantinlatour answered 30/7, 2014 at 16:34 Comment(5)
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.Cynical
@Cynical : true, but the actions needed to turn the statements here into expressions would complete destroy the goal of making this a "shorthand"Fantinlatour
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.Cynical
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.Sleekit
@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.Fantinlatour
I
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.

Intercalary answered 30/7, 2014 at 16:36 Comment(1)
the motivation was an interest, I am still going to stick with if else. but thanks for the comment anyway :)Wesla
C
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.

Cynical answered 30/7, 2014 at 16:35 Comment(1)
See my comment to the other answer regarding conflating having a value with being an expression.Sleekit
G
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

Gelderland answered 30/7, 2014 at 16:48 Comment(3)
This isn't assigning the relevant string literals to the appropriate name variables.Cynical
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.Gelderland
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.Cynical

© 2022 - 2024 — McMap. All rights reserved.