king yau king yau - 3 months ago 8
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


or

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

Answer

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.

Example: https://dotnetfiddle.net/

Comments