Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Interpolation with format variable

Tags:

c#

c#-6.0

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.

like image 563
CallMeLaNN Avatar asked Sep 02 '15 18:09

CallMeLaNN


People also ask

How do you interpolate a string?

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.

Which strings do interpolate variables?

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.

What happens if you use NULL value in string interpolation?

If the interpolation expression evaluates to null , an empty string ("", or String.

Why is s used in Scala?

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.


1 Answers

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.

like image 75
i3arnon Avatar answered Oct 02 '22 19:10

i3arnon