C# String Interpolation

by Miguel de Icaza

We have discussed in the past adding support to C# to support string interpolation. I have cooked a patch that allows C# developers to embed expressions inside strings, like this:

	var a = 'Hello {name} how are you?';
	

Single quotes are used for strings that will have expressions interpolated between the braces. The above sample is equivalent to:

	var a = String.Format ("Hello {0} how are you?", name);
	

Currently the patch supports arbitrary expressions in the braces, it is not limited to referencing variables:

	var a = 'There are {list.Count} elements';
	

This notation can be abused, this shows a LINQ expression embedded in the string:

	var a = 'The {(from x in args where x.StartsWith ("a") select x).FirstOrDefault ()} arguments';
	

I am not familiar with what are the best practices for this sort of thing in Python, Ruby and other languages. Curious to find out.

Update: after the discussion on the comments the syntax was changed to use $" instead of the single quote to denote a string that will be interpolated. Now you will write:

	var a = $"There are {list.Count} elements";
	var greeting = $"Hello {name} how are you?";
	

The updated patch is here.

Posted on 20 Dec 2009