king yau king yau - 1 year ago 119
C# Question

how to select one value if true or false in C#?

I am new to C#. Is there any function to do these? (can anyone tell me how to call this? )

For example:

string str = boolVar: "trueA" || "falseA";// if boolVar = true => return string trueA


var abb = booVar: "stringIfTrue" || 3.14; //if boolVar == false => return double 3.14

Answer Source

As Tim has shown the first case can easily be done with the conditional operator (sometimes also called ternary operator).

If you really, really, really want to make the second line work as well you can use .NET's dynamic type:

dynamic abb = booVar? "stringIfTrue" : (dynamic)3.14;

You have to cast at least one of the last two operands to (dynamic) though.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download