String Interpolation with format variable

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.


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

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.

Tags:

C#

C# 6.0