[C# 6] Expression-level Features

C# 6 added many new expressions such as string interpolation, nameof expressions, null-conditional operators, and Index initializers.

 1. String Interpolation

String formatting has been relied on String.Format() method. C# 6 lets you format strings more easily. String.Format() is based on the index for its mapping. The interpolated strings ($”…”) put the variables right in the string.
var homer = new
    Name = "Homer Simpson",
    Age = 35
var maggie = new
    Name = "Maggie Simpson",
    Age = 1

Assert.AreEqual("Homer Simpson is 35 years old.",
    $"{homer.Name} is {homer.Age} years old.");
Assert.AreEqual("       Homer Simpson is 35 years old.",
    $"{homer.Name, 20} is {homer.Age} years old."); // alignment
Assert.AreEqual("Homer Simpson is 035 years old.",
    $"{homer.Name} is {homer.Age:D3} years old."); // format
Assert.AreEqual("Maggie Simpson is 1 year old.",
    $"{maggie.Name} is {maggie.Age} year{(maggie.Age == 1 ? "" : "s")} old."); // expression


2. nameof Expressions

The nameof() expression is used to obtain the simple name of a variable or a method. It can be used for argument validation or property changed events. The main purpose of this expression is to keep your code valid when renaming definitions. Unlike hard-coded names, the compile error occurs when the variable name is changed.
class MyProduct
    public string Name { get; set; }
    public string GetProductName() => $"Product is {this.Name}";

var product = new MyProduct() { Name = "Toy" };
Assert.AreEqual("product", nameof(product));
Assert.AreEqual("Name", nameof(product.Name));
Assert.AreEqual("GetProductName", nameof(product.GetProductName));


3. Null-conditional Operator

 The null-conditional operator is syntactic sugar. The following expressions are the same.
string value = (val != null) ? val.Trim() : null;
string value = val?.Trim();
It is also used together with the null-coalescing operator ”??’.
product.Name = null;
Assert.AreEqual(0, product.Name?.Length ?? 0);
 I found this is quite useful.


4. Index Initializers

 Initializing Dictionary was always cumbersome. Now you can specify indexed elements if the collection supports indexing.
var numbers = new Dictionary
    [3] = "Three",
    [1] = "One",
    [7] = "Seven"
Assert.AreEqual("One", numbers[1]);
Assert.AreEqual("Seven", numbers[7]);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s