10

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?

Eugene
  • 10,957
  • 20
  • 69
  • 97
John Bustos
  • 19,036
  • 17
  • 89
  • 151
  • 1
    related : https://stackoverflow.com/questions/39874172/dynamic-string-interpolation – Ehsan Sajjad Mar 21 '18 at 16:10
  • 1
    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()}`. – Jeroen Mostert Mar 21 '18 at 16:13
  • Thanks, @EhsanSajjad - Sad, it would be a cool addition, but makes sense. – John Bustos Mar 21 '18 at 16:15
  • LOL @JeroenMostert - Good point. I guess I just didn't understand how interpolated string worked. Makes sense now, though. – John Bustos Mar 21 '18 at 16:17
  • 2
    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. – Eric Falsken Sep 12 '19 at 00:12

1 Answers1

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));
Ali Ezzat Odeh
  • 2,093
  • 1
  • 17
  • 17
  • 1
    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!! – John Bustos Mar 21 '18 at 16:09
  • 2
    @JohnBustos interpolation is compile time thing, it needs those placeholder available so i think you can't use it via config – Ehsan Sajjad Mar 21 '18 at 16:12