0

I used to write this

if (condition)
{
    str = "A";
}
else
{
    str = "B";
}

finalstr = "Hello "+str;

I wonder if there is a better way.

What I want is

finalstr = "Hello "+ if (condition) {str = "A"} else {str = "B"};

or

finalstr = "Hello "+ condition ? "A" : "B";

Something like $var = "Hello ".if(condition)... in php.

Is there a similar way to put a condition right into a string?

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • 4
    You were there -- it's just a precedence issue. `finalstr = "Hello " + (condition ? "A" : "B");` – canton7 Oct 22 '21 at 14:01
  • 3
    You're looking for [string interpolation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated): `finalstr = $"Hello { (condition ? "A" : "B") }";` – D M Oct 22 '21 at 14:02
  • @DM example is the proper way of doing things with strings, get used to it – Kęstutis Ramulionis Oct 22 '21 at 14:03
  • 3
    @Wyck https://stackoverflow.com/questions/31844058/how-to-use-the-ternary-operator-inside-an-interpolated-string - You can't use a ternary expression directly in string interpolation because the colon (`:`) is already used for format strings. – D M Oct 22 '21 at 14:11
  • I think this if-else is pretty good. – urlreader Oct 22 '21 at 14:33

2 Answers2

0

You can do:

finalstr = "Hello " + (condition ? "A" : "B");

or

finalstr = $"Hello { (condition ? "A" : "B") }";

or using string.Format

finalstr = string.Format("Hello {0}", condition ? "A" : "B");

or you can create an extension that suits your needs:

public static class StringExtension
{
    // it's not needed since C# supports ternary, but I did it anyway 
    public static string If(this string str, Func<string, string> condition)
    {
        return string.IsNullOrWhiteSpace(str) ? str : $"{str} {condition(str)}";
    }
}

then you can do this:

finalstr = "Hello".If(x => x == str ? "A" : "B");
D M
  • 5,769
  • 4
  • 12
  • 27
iSR5
  • 3,274
  • 2
  • 14
  • 13
-1

On simple numeric example of condition, for more then 2 outcomes:

var c = 1; // Algorithm / console input / etc...

var result = "hello " + c switch
{
    1 => "variant a",
    2 => "variant b",
    _ => "default variant if there is no specific match"
};

Said condition does not have to be numeric, this pattern works with basically everything else.

quain
  • 861
  • 5
  • 18
  • 5
    This is still going to be rather more complex than either of the options in the comments, for the question which was asked - i.e. based on a Boolean condition. – Jon Skeet Oct 22 '21 at 14:14