C# FormattableString concatenation for multiline interpolation
Asked Answered
B

1

20

In C#7, I'm trying to use a multiline interpolated string for use with FormttableString.Invariant but string concatenation appears to be invalid for FormttableString.

Per the documentation: A FormattableString instance may result from an interpolated string in C# or Visual Basic.

The following FormttableString multiline concatenation does not compile:

using static System.FormattableString;
string build = Invariant($"{this.x}" 
                       + $"{this.y}"
                       + $"$this.z}");

Error CS1503 - Argument 1: cannot convert from 'string' to 'System.FormattableString'

Using an interpolated string without concatenation does compile:

using static System.FormattableString;
string build = Invariant($"{this.x}");

How do you implement multiline string concatenation with the FormattableString type?

(Please note that FormattableString was added in .Net Framework 4.6.)

Brahmani answered 12/10, 2018 at 23:52 Comment(4)
Can you include the provided reason why it doesn't compile?Orpington
@John, the error code has been added.Brahmani
$"{this.x}" is a string, string interpolation is just a syntactic sugar for string format and in this case it doesn't do anything, it's same as using this.x, you are trying to pass a string while FormattableString is expected as the error message tells youChemotaxis
@SelmanGenç - A nonconcatenated interpolated string works fine though.Brahmani
C
18

The Invariant method is expecting the parameter of FormattableString type. In your case, the parameter $"{this.x}" + $"{this.y}" becomes "string" + "string' which will evaluate to string type output. That's the reason you are getting the compile error as Invariant is expecting the FormattableString and not string.

You should try this for single line text -

public string X { get; set; } = "This is X";
public string Y { get; set; } = "This is Y";
public string Z { get; set; } = "This is Z";
string build = Invariant($"{this.x} {this.y} {this.z}");

Output -

This is X This is Y This is Z

And to implement multiline interpolation, you can build the FormattableString like below and then use the Invarient.

FormattableString fs = $@"{this.X}
{this.Y}
{this.Z}";
string build = Invariant(fs);

Output -

This is X

This is Y

This is Z

Coerce answered 13/10, 2018 at 0:25 Comment(4)
Per the documentation: A FormattableString instance may result from an interpolated string in C# or Visual Basic.Brahmani
Yes, but you are trying to concatenate 2 interpolated strings which will evaluate to string not FormattableString, updated answer.Coerce
How would you implement a multliline concatenated interpolated string as a FormattableString? What would be the proper way to concatenate interpolated strings for use as a FormattableString?Brahmani
updated my answer, now for multliline concatenation.Coerce

© 2022 - 2024 — McMap. All rights reserved.