What's New in C# 6、New Language Features in C# 6 をベースに、C# 5 と比較してコードがどう変わるのかを、主な機能に絞って記載しています。
1. 自動プロパティの機能強化 (Auto-Property enhancements)
自動プロパティの初期化子 (Auto-Property initializers)
old
public class Customer {
public Customer() {
First = "Jane";
Last = "Doe";
}
public string First { get; set; }
public string Last { get; set; }
}
new!
public class Customer {
public string First { get; set; } = "Jane";
public string Last { get; set; } = "Doe";
}
読み取り専用の自動プロパティ (Read-only auto-properties)
old
public class Customer {
private readonly string _name;
public Customer(string name) {
_name = name;
}
public string Name { get { return _name; } }
}
new!
public class Customer {
public Customer(string name) {
Name = name;
}
public string Name { get; }
}
2. 式形式のメンバー (Expression-bodied function members)
式形式のメソッド (Expression bodies on method-like members)
old
public void Print() {
Console.WriteLine(First + " " + Last);
}
new!
public void Print() => Console.WriteLine(First + " " + Last);
式形式のプロパティ (Expression bodies on property-like function members)
old
public string Name {
get {
return First + " " + Last;
}
}
new!
public string Name => First + " " + Last;
3. using static
old
using System;
class Program {
static void Main() {
Console.WriteLine(Math.Sqrt(3*3 + 4*4));
Console.WriteLine(DayOfWeek.Friday - DayOfWeek.Monday);
}
}
new!
using static System.Console;
using static System.Math;
using static System.DayOfWeek;
class Program {
static void Main() {
WriteLine(Sqrt(3*3 + 4*4));
WriteLine(Friday - Monday);
}
}
4. Null 条件演算子 (Null-conditional operators)
old
var handler = PropertyChanged;
if (handler != null) {
handler(this, args);
}
new!
PropertyChanged?.Invoke(this, args);
5. 文字列補間 (String interpolation)
old
var s = String.Format("{0,20} is {1:D3} year{2} old", p.Name, p.Age, (p.Age == 1 ? "" : "s"));
new!
var s = $"{p.Name,20} is {p.Age:D3} year{(p.Age == 1 ? "" : "s")} old";
6. nameof
式 (nameof
Expressions)
old
if (x == null) throw new ArgumentNullException("x");
new!
if (x == null) throw new ArgumentNullException(nameof(x));
7. インデックス初期化子 (Index initializers)
old
var numbers = new Dictionary<int, string> {
{7, "seven"},
{9, "nine"},
{13, "thirteen"},
};
new!
var numbers = new Dictionary<int, string> {
[7] = "seven",
[9] = "nine",
[13] = "thirteen",
};
8. 例外フィルター (Exception filters)
old
try { … }
catch (MyException e) {
if (myfilter(e)) {
…
}
}
new!
try { … }
catch (MyException e) when (myfilter(e)) {
…
}
9. catch / finally ブロックでの await (Await in catch and finally blocks)
old
Resource res = null;
try {
res = await Resource.OpenAsync(…);
…
}
catch(ResourceException e) {
Resource.LogAsync(res, e).Wait();
}
finally {
if (res != null) {
res.CloseAsync().Wait();
}
}
new!
Resource res = null;
try {
res = await Resource.OpenAsync(…);
…
}
catch(ResourceException e) {
await Resource.LogAsync(res, e);
}
finally {
if (res != null) {
await res.CloseAsync();
}
}