C# - What is string interpolation?

String interpolation is a language feature of the C# compiler. It is new C# version 6.0. It requires Visual Studio 2015 or higher.

String interpolation replaces positional parameters with embedded expressions.


The two strings below are equivalent.


  // Some common variables
  var cat = "cat";
  var mat = "mat";
  DateTime now = DateTime.Now;
  string str;
  
  // Using String.format
  str = String.Format("The {0} sat on the {1}. Today is {2:dddd MMM dd}", cat, mat, now);
  
  // Using C# 6.0 string interpolation
  str = $"The {cat} sat on the {mat}. Today is {now:dddd MMM dd}";
  

How is string interpolation implemented in C#?

String interpolation is a feature of the C# compiler and not of the runtime. The generated IL code is identical to string.format.



  // Some common variables
  ldstr       "cat"
  stloc.0     // cat
  ldstr       "mat"
  stloc.1     // mat
  call        System.DateTime.get_Now
  stloc.2     // time
  
  // Using String.format
  ldstr       "The {0} sat on the {1}. Today is {2:dddd MMM dd}"
  ldloc.0     // cat
  ldloc.1     // mat
  ldloc.2     // time
  box         System.DateTime
  call        System.String.Format
  stloc.3     // str
  
  // Using C# 6.0 string interpolation
  ldstr       "The {0} sat on the {1}. Today is {2:dddd MMM dd}"
  ldloc.0     // cat
  ldloc.1     // mat
  ldloc.2     // time
  box         System.DateTime
  call        System.String.Format
  stloc.3     // str
  

Why use string interpolation?

  • It produces cleaner, more readable code.
  • It reduces programmer errors. The format string is checked at compile time.

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath