String Interpolation with format variable

Solution 1:

No, you can't use string interpolation with something other than a string literal as the compiler creates a "regular" format string even when you use string interpolation.

Because this:

string name = "bar";
string result = $"{name}";

is compiled into this:

string name = "bar";
string result = string.Format("{0}", name);

the string in runtime must be a "regular" format string and not the string interpolation equivalent.

You can use the plain old String.Format instead.

Solution 2:

One approach to work around that would be to use a lambda containing the interpolated string. Something like:

Func<string, string> formatter = url => $"URL: {url}";
...
var googleUrl = "http://google.com";
...
var log = formatter(googleUrl);

In C# 7.0, you could use a local function instead of a lambda, to make the code slightly simpler and more efficient:

string formatter(string url) => $"URL: {url}";
...
var googleUrl = "http://google.com";
...
var log = formatter(googleUrl);

Solution 3:

String interpolation is not library, but a compiler feature starting with C# 6.

The holes are not names, but expressions:

var r = new Rectangle(5, 4);
var s = $"Area: {r.Width * r.Heigh}":

How would you do that for localization, as you intend to?

Even r only exists at compile time. In IL it's just a position on the method's variable stack.

I've done what you intend to do for resources and configuration files.

Since you can only have a finite set of "variables" to substitute, what I did was have an array (or dictionary, if you prefer) and use a regular expression to replace the names in the holes with its index. What I did even allowed for format specifiers.

Solution 4:

This is supposed to be a comment to the answer from i3arnon but I do not have the reputation :-( : But for those who come to this old thread, in string.Format the format can be a variable:

string name = "bar";
string format = "{0}";
string result = string.Format(format, name);

works.