Search code examples
c#variablesif-statementinitializationshorthand-if

initialization of two variables at the same time


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;

Solution

  • 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.