39

I can do this:

var log = string.Format("URL: {0}", url);

or even like this

var format = "URL: {0}";
...
var log = string.Format(format, url);

I have a format defined somewhere else and use the format variable, not inline string.

In C# 6, this is seems impossible:

var format = $"URL: {url}"; // Error url does not exist
...
var url = "http://google.com";
...
var log = $format; // The way to evaluate string interpolation here

Is there anyway to use string interpolation with variable declared earlier?

C# 6 seems interpolate the string inline during compile time. However consider using this feature for localization, define a format in config or simply having a format const in a class.

2
  • You can't do that. Just use string.Format. Commented Sep 2, 2015 at 18:23
  • You have to use 'the old way' you have been using or wrap it into private method. Commented Sep 2, 2015 at 18:24

7 Answers 7

50

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I agreed. I thought logically "{name}" to "{0}" mapping can be done in run-time at the first place but the string.Format parameters should be compiled inline. So I can't simply introduce new {name2} dynamically in variable.
but at least it should accept const string. The compiler then can find-out the "{...}" token and construct the string.Format parameters. Anyway, not a big deal.
@CallMeLaNN this would work only if the const was defined inside the method, so that the compiler could resolve (and validate) the placeholders. Otherwise, how could the compiler decide whether a class-level constant string was valid, if its placeholders existed only inside methods?
35

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

Comments

5

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.Height}":

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.

1 Comment

The localization part is "area: " in your example. However +1 for mention about expression.
2

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.

Comments

1

You can with the right Nuget package: https://www.nuget.org/packages/InterpolatedStringFormatter

var mystring = "a thing(and something {other})";
Console.WriteLine(mystring.Interpolate("else"));

Outputs:

a thing(and something else)

Comments

0

More of an idea as opposed to an answer.

For the example shown in the question, you can do the following.

var format = "URL: ";
...
var url = "http://google.com";
...
var result= $"{format} {url}";

I have an actual project where I have to do something like this a lot:

var label = "Some Label";
var value = "SomeValue";

//both label & value are results of some logic

var result = $"{label}: {value}";

Comments

-6

It seems that you can do it like this:

var googleUrl = "http://google.com";
var url = $"URL: {googleUrl}";

System.Console.WriteLine(url);

You can check for more details in https://msdn.microsoft.com/en-us/library/dn961160.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.