Awesome string formatting
The next release of C# 6 has some amazing new features. In a series of blog posts I will cover some of them.
- Chained null checks
- The nameof operator
- Awesome string formatting (this one)
- Expression-bodied methods
- Auto-property initializers
- Initialize a Dictionary with index initializers
Using the versatile string.Format
required a lot of typing and keeping the numbed placeholders in sync with the method parameters.
var numerator = 1;
var denominator = 2;
Console.WriteLine("Fraction {0}/{1}", numerator, denominator);
// Output:
// Fraction 1/2
In C# 6 is it a lot easier with String interpolation:
var numerator = 1;
var denominator = 2;
Console.WriteLine("Fraction {numerator}/{denominator}");
// Output:
// Fraction 1/2
Referencing the variable, property or field directly within the string. It is even possible to access properties or use expressions.
public class Person
{
public string Name { get; set; }
public Address HomeAddress { get; set; }
public override string ToString()
{
return string.Format("{Name} lives in {HomeAddress.City}.");
}
}
The string.Format
is not event needed, but use the shorthand notation $.
return $("{Name} lives in {HomeAddress.City}.";
This is easily combinable with an expression and the null-conditional operator (?.) operator.
return $"{Name} lives in {HomeAddress?.City ?? "City unknown"}.";
Comments