c# – Prefix before string: '$'


I searched my entire C # reference and couldn't find what '$' is.

I only realized that it is somewhat similar to verbatim string '@'.


How does this affect the string?


The $ prefix in front of a string indicates that an interpolated string follows.

Interpolation is used for convenient string construction. In this case, the expression of interpolated strings can look like a string template in which language expressions can be used.

Interpolated strings are easier to understand with respect to arguments than composite formatting


var s = $"Name = {name}, hours = {hours:hh}";

Compared to string.Format

var s = string.Format("Name = {0}, hours = {1:hh}", name, hours);    

An important difference from the same string.Format :

String interpolation is transformed at compile time to invoke an equivalent string.Format call. This leaves in place support for localization as before (though still with traditional format strings) and doesn't introduce any post compile injection of code via strings.

The interpolated string is transformed at compile time into an equivalent call to string.Format . This leaves localization support as before (albeit still with traditional string formatting) and does not allow any code injection to be added to the string after compilation.

This feature appeared with the release of C # 6 .

More details can be found in the help on MSDN.

Scroll to Top