initialization of two variables at the same time

320 Views Asked by At

Is there any way to initialize these two variable at the same time?

in this example "time" variable can be "" or has a value.

var variable1 = string.IsNullOrEmpty(time) ? string.Empty : "value";
var variable2 = string.IsNullOrEmpty(time) ? "value" : string.Empty;
4

There are 4 best solutions below

0
Konrad Kokosa On BEST ANSWER

Not possible. But you can create some helper class to hold those two variables. Or you can use some out-of-the-box, like Tuple:

var variable = string.IsNullOrEmpty(time) ? Tuple.Create(string.Empty, "value") 
                                          : Tuple.Create("value", string.Empty);

and then access those two values as variable.Item1 and variable.Item2.

Note: Use it wisely as variables are in general better because they have names, and hence - some meaning. Too many Tuples with all those Item1 and Item2 can fast become unclear, what they are intended for.

0
Alan B On

No. Assuming "value" is the same in both cases the most you could do is replace "value" with variable1 in the second line.

1
Allan Elder On

It is possible to initialize multiple variables on a single line of code to the same value:

    string variable2;
    var variable1 = variable2 =(string.IsNullOrEmpty(time) ? string.Empty : "value");

However, I think this is unreadable and would avoid it.

With what you are trying to do (from your comment), I would use a simple if statement so that the IsNullOrEmpty check is only executed once.

    string variable1;
    string variable2;
    if (string.IsNullOrEmpty(time))
    {
        variable1 = null;
        variable2 = "value";
    }
    else
    {
        variable1 = "value";
        variable2 = null;
    }
0
RobH On

Here you go, a completely unreadable mess:

string time = null;

string variable1, variable2 = (variable1 = string.IsNullOrEmpty(time) ? string.Empty : "value") == string.Empty ? "value" : string.Empty;

In case you couldn't tell, this isn't a serious suggestion.