C# – How to Use the ternary operator in String Interpolation ?

Everwondered how you can use a ternary operator with-in a string interpolation in C#?. This simple tip shows you how you can do it.

Assume that you have a variable isArchitect and you would like to set a text Yes when the value is set with-in the interpolated string.

One of the simplest option is to first use the ternary operator and set the string as shown below.

var architectResult = isArchitect ? " Yes" : "No";
var result = $"{fieldName}{architectResult}";

How to use Ternary Operator in Interpolated String in C# ?

If you need them in the single line with-in the string interpolation, you will need to wrap the condition in parenthesis as shown below.

var result = $"Architect : {(isArchitect ? "yes" : "no")}";

Here’s the complete code snippet demonstrating the usage of ternary operator with-in the interpolation string.

public class Hello {
    public static void Main() {
        var isArchitect = true;
        var result = $"Architect : {(isArchitect ? "yes" : "no")}";
        System.Console.WriteLine(result);
    }
}

Output

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...