Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use if conditional in interpolation string

I have a value that I only obtain if a checkbox is checked like:

var currentEmployeeMedian = "";

if (chkGetMedian.Checked)
{
    //code there
    currentEmployeeMedian = EmployeeMedian.Median.ToString();
}

So I have an interpolation like:

$"{employee}: {formattedTime} - Employee Median = {currentEmployeeMedian} minutes";

But I only want to show - Employee Median = {currentEmployeeMedian} minutes when checkbox is checked is there any way to achieve this without using if else clause? there is no interpolation achievement like use ?and :

if clause it just like:

if (chkGetMedian.Checked)
{
     $"{employee}: {formattedTime} - Employee Median = {currentEmployeeMedian} minutes";
}
else
{
    $"{employee}: {formattedTime}";
}

is not possible to do this but with only interpolation?

like image 399
Rene Avatar asked Sep 18 '25 01:09

Rene


1 Answers

So your goal is to optionally include the latter half of an interpolated string without an if statement. You tried the ternary operator, but you failed because interpolated strings can't be nested.

Hopefully, I understood your problem correctly.

The solution is to create a string variable that holds the latter half:

var medianString = $" - Employee Median = {currentEmployeeMedian} minutes";
$"{employee}: {formattedTime}{(chkGetMedian.Checked ? medianString : string.Empty)}"
like image 199
Sweeper Avatar answered Sep 19 '25 13:09

Sweeper