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
You can use the conditional operator ?:
string result = boolVar ? "stringIfTrue" : "stringIfFalse";
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With