I've faced an issue with nested string interpolation in C# 6.
For example, there is a string:
string test = "StartText MiddleText1 MiddleText2 EndText";
If I want to apply ToUpper() method for MiddleText1 only, I can do this way:
string test = $@"StartText {"MiddleText1".ToUpper()} MiddleText2 EndText";
But what if I want to apply a string method, for example Replace() for this part of string:
{"Middletext1".ToUpper()} MiddleText2
I expected that something like this will work:
string test = $@"StartText {"{"MiddleText1".ToUpper()} MiddleText2".Replace("x", "y")} EndText";
But this syntax is wrong - I've tried a lot variations, played with quotas but I couldn't get correct syntax for this purpose. I'd wish to not split the string in a different parts. Is there a way to solve it using interpolation feature only?
Stop trying to do everything in one line is my suggestion
The following is the answer
var middle = "MiddleText1";
middle = middle.ToUpper();
var middle2 = $"{middle} MiddleText2";
middle2 = middle2.Replace("x", "y");
string test = $"StartText {middle2} EndText";
Which, when you add it all together.
string test = $"StartText {$"{"MiddleText1".ToUpper()} MiddleText2".Replace("x", "y")} EndText";
In short, you were just missing a $
However, Even this is messy as i am not sure what all the replaces are for, where this text comes from, and what the issue is you are trying to solve
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