Question

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");
     }
Was it helpful?

Solution

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.

OTHER TIPS

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.

No.

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

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top