298

I have been looking over some C# exercises in a book and I ran across an example that stumped me. Straight from the book, the output line shows as:

Console.WriteLine($"\n\tYour result is {result}.");

The code works and the double result shows as expected. However, not understanding why the $ is there at the front of the string, I decided to remove it, and now the code outputs the name of the array {result} instead of the contents. The book doesn't explain why the $ is there, unfortunately.

I have been scouring the VB 2015 help and Google, regarding string formatting and Console.WriteLine overload methods. I am not seeing anything that explains why it is what it is. Any advice would be appreciated.

jordanz
  • 367
  • 4
  • 12
BigTime
  • 3,007
  • 2
  • 11
  • 5
  • 21
    [Interpolated Strings](https://msdn.microsoft.com/en-us/library/dn961160.aspx) – Eser Oct 01 '15 at 02:34
  • 1
    One would have to presume that 'result' is of the datatype 'double' as you have not mentioned it. – Pramod Mangalore Oct 01 '15 at 02:35
  • 2
    Not sure why, but this post seems to have much higher search relevance than its dupe target. This seems to be a good case for keeping dupes around. – jrh Jan 05 '18 at 15:19
  • 1
    **Short answer**: String.Format("Somestring {0}", SomeValue) becomes $"Somestring {SomeValue}" – Shadi Alnamrouti Jan 03 '19 at 08:12
  • If you're known with es6 you can use `${variable}` it is almost similiar, because you can add a string with a variable at the same line. like int age = 21; example: $"I am {age} years old." – Valdemar Vreeman Jun 08 '21 at 09:12

2 Answers2

435

It's the new feature in C# 6 called Interpolated Strings.

The easiest way to understand it is: an interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions' results.

For more details about this, please take a look at MSDN.

Now, think a little bit more about it. Why this feature is great?

For example, you have class Point:

public class Point
{
    public int X { get; set; }

    public int Y { get; set; }
}

Create 2 instances:

var p1 = new Point { X = 5, Y = 10 };
var p2 = new Point { X = 7, Y = 3 };

Now, you want to output it to the screen. The 2 ways that you usually use:

Console.WriteLine("The area of interest is bounded by (" + p1.X + "," + p1.Y + ") and (" + p2.X + "," + p2.Y + ")");

As you can see, concatenating string like this makes the code hard to read and error-prone. You may use string.Format() to make it nicer:

Console.WriteLine(string.Format("The area of interest is bounded by({0},{1}) and ({2},{3})", p1.X, p1.Y, p2.X, p2.Y));

This creates a new problem:

  1. You have to maintain the number of arguments and index yourself. If the number of arguments and index are not the same, it will generate a runtime error.

For those reasons, we should use new feature:

Console.WriteLine($"The area of interest is bounded by ({p1.X},{p1.Y}) and ({p2.X},{p2.Y})");

The compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

For the full post, please read this blog.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Triet Doan
  • 11,455
  • 8
  • 36
  • 69
  • 9
    "If you need to add a new item to the string (not to the end), you have to update the whole indexing number." Well, that's not true. It doesnt have to be in order. – Thomas Mar 30 '16 at 13:28
  • That sentence is about `string.Format()` :) – Triet Doan Mar 30 '16 at 15:12
  • 18
    Yes. You can easily add {4} before {0} :) – Thomas Mar 31 '16 at 09:42
  • I personally just like utilizing String.Concat(). It seems to be the simplest way without adding brackets and easy to understand and update. – ScubaSteve Jun 02 '16 at 13:56
  • I prefer (n + " sheep") to ("{0} sheep", n). – alan2here Aug 08 '16 at 18:37
  • 13
    "You have to maintain the index yourself. If the number of arguments and index are not the same, it will generate error." I think it's important to note that this will be a runtime error that won't be caught by the compiler. – aaaantoine Oct 07 '16 at 18:07
  • 7
    @alan2here If you use more than one variable, eg `n + " sheep, " + m + " chickens"`, you're creating multiple string instances in memory. One with `n+sheep`, then `n+sheep+m`, then the final output. Remember that string are immutable and can't be GC'd. In short, if you use your code in a tight loop, you could end up wasting many megabytes of memory for no reason (this is why the `StringBuilder` class was created.) – Basic Oct 10 '16 at 03:33
  • 1
    Strings are immutable and CAN be GC'd - They just can't be changed. If you do a string.Format() and it generates a string, you can use it, and when you stop referencing it, then it gets GC'ed. If it didn't C# would be nearly useless. (Using multiple strings like above does give you lots of strings to feed to GC though.) – Traderhut Games Feb 18 '17 at 20:44
62

String Interpolation

is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):

It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.

A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.

Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.

{<interpolatedExpression>[,<alignment>][:<formatString>]}  

Where:

  • interpolatedExpression - The expression that produces a result to be formatted
  • alignment - The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression. If positive, the string representation is right-aligned; if negative, it's left-aligned.
  • formatString - A format string that is supported by the type of the expression result.

The following code example concatenates a string where an object, author as a part of the string interpolation.

string author = "Mohit";  
string hello = $"Hello {author} !";  
Console.WriteLine(hello);  // Hello Mohit !

Read more on C#/.NET Little Wonders: String Interpolation in C# 6

Community
  • 1
  • 1
Mohit S
  • 13,723
  • 6
  • 34
  • 69
  • I could be incorrect, can't find the docs at the moment, but the statement the `...compiler treats like String.Format() behind the scenes` I don't think applies anymore to more current versions of C#. The results between using `$""` and `string.Format` are more or less the same, but behind the scenes they aren't carried out in the same way. – Snap Apr 20 '22 at 06:56