Search code examples
c#string-formattingformattablestring

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?


Solution

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