John Bustos
John Bustos

Reputation: 19544

C# Convert string variable to FormattableString

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?

Upvotes: 11

Views: 17670

Answers (1)

Ali Ezzat Odeh
Ali Ezzat Odeh

Reputation: 2163

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));

Upvotes: 2

Related Questions