Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
like image 739
king yau Avatar asked Jan 06 '23 10:01

king yau


2 Answers

You can use the conditional operator ?:

string result = boolVar ? "stringIfTrue" : "stringIfFalse";
like image 162
Tim Schmelter Avatar answered Jan 13 '23 14:01

Tim Schmelter


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/

like image 37
Good Night Nerd Pride Avatar answered Jan 13 '23 15:01

Good Night Nerd Pride