C# Convert string variable to FormattableString
Asked Answered
E

1

11

Suppose, in a C# program, I have the following lines in my app.config:

<appSettings>
    <add key="FormattedString" value="{greeting}, {name}." />
</appSettings>

And, in my code, I am using it as follows:

    private void doStuff()
    {
        var toBeFormatted = ConfigurationManager.AppSettings["FormattedString"];
        string greeting = @"Hi There";
        string name = @"Bob";
    }

And I would like to use the toBeFormatted variable as a FormattableString to be able to insert the variables via string interpolation - Something along the lines of:

Console.WriteLine(toBeFormatted);

I've tried things such as:

var toBeFormatted = $ConfigurationManager.AppSettings["FormattedString"];

or

Console.WriteLine($toBeFormatted);

But both are causing errors. Is there a way to let the compiler know the toBeFormatted string should be used as a FormattableString?

Embrey answered 21/3, 2018 at 15:59 Comment(5)
related : #39874672Chandigarh
Obviously, no. I say "obviously" because, well, the compiler would need to compile the replacement expressions at runtime, which I suppose is possible, but it would be really awkward and inefficient. Also consider the horrors of {MySuperDangerousMethodThatFormatsYourHardDriveAndReturnsAnInt()}.Milne
Thanks, @EhsanSajjad - Sad, it would be a cool addition, but makes sense.Embrey
LOL @JeroenMostert - Good point. I guess I just didn't understand how interpolated string worked. Makes sense now, though.Embrey
It's worth pointing out that the FormattableStringFactory.Create can do some of the job of the compiler, but I still can't get it to evaluate property expressions.Peristalsis
M
2

Well, in case it doesn't I suggest the following simple solution:

<appSettings>
   <add key="FormattedString" value="{0}, {1}." />
</appSettings>

then in your code:

Console.WriteLine(string.Format(toBeFormatted,greeting, name));
Mcghee answered 21/3, 2018 at 16:8 Comment(2)
Thanks so much. I knew of this one, I was just hoping there was still a way to use string interpolation over String.Format. Thanks!!Embrey
@JohnBustos interpolation is compile time thing, it needs those placeholder available so i think you can't use it via configChandigarh

© 2022 - 2024 — McMap. All rights reserved.