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.
Structure of an interpolated string. To identify a string literal as an interpolated string, prepend it with the $ symbol. You can't have any white space between the $ and the " that starts a string literal. To concantenate multiple interpolated strings, add the $ special character to each string literal.
String interpolation is common in many programming languages which make heavy use of string representations of data, such as Apache Groovy, Julia, Kotlin, Perl, PHP, Python, Ruby, Scala, Swift, Tcl and most Unix shells.
If the interpolation expression evaluates to null , an empty string ("", or String.
s is a method Scala provides other off-the-shelf interpolation functions to give you more power. You can define your own string interpolation functions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With