LoginSignup
1
2

More than 3 years have passed since last update.

C# 6.0 の記述方法

Posted at

C# 6.0 の新機能

読み取り専用の自動プロパティ (Read-only auto-properties)

自動実装プロパティで読み取り専用を記述できるようになった。

class Person
{
    public DateTime Birth { get; } = new DateTime(1999, 12, 31);
}

以前の書き方

フィールドを用意する必要があった。
class Person
{
    private DateTime birth = new DateTime(1999, 12, 31);
    public DateTime Birth 
    {
        get { return this.birth; }
    }
}

自動プロパティ初期化子 (Auto-property initializers)

自動実装プロパティの初期値を指定できるようになった。

class Person
{
    public DateTime Birth { get; set; } = new DateTime(1999, 12, 31);
}

以前の書き方

コンストラクタで初期化する必要があった。
class Person
{
    public Person()
    {
        this.Birth = new DateTime(1999, 12, 31);
    }

    public DateTime Birth { get; set; }
}

ラムダ式によるメソッドとプロパティ (Expression-bodied function members)

メソッド (Methods)

簡単なメソッドを1行で書けるようになった。

class Person
{
    private DateTime birth = new DateTime(1999, 12, 31);
    public int GetAge() => DateTime.Today.Year - this.birth.Year + 1; // 数え年
}

以前の書き方

1行で書けなかった。
class Person
{
    private DateTime birth = new DateTime(1999, 12, 31);
    public int GetAge()
    {
        return DateTime.Today.Year - this.birth.Year + 1; // 数え年
    }
}

using static

static クラスのメソッド呼び出し等に、クラス名が省略可能になった。

using static System.Math;

static class Util
{
    public static int Range(int value, int lower, int upper)
    {
        return Max(Min(value, lower), upper);
    }
}

Null 条件演算子 (Null-conditional operators)

イベント発生等を簡潔に書けるようになった。

class Person
{
    private string name;
    public string Name
    {
        get { return this.name; }
        set
        {
            this.name = value;
            this.NameChanged?.Invoke(this, EventArgs.Empty);
        }
    }

    public event EventHandler NameChanged;
}

以前の書き方

null チェックの必要があった。
class Person
{
    private string name;
    public string Name
    {
        get { return this.name; }
        set
        {
            this.name = value;
            var handler = this.NameChanged;
            if (handler != null) handler(this, EventArgs.Empty);
        }
    }

    public event EventHandler NameChanged;
}

文字列補間 (String interpolation)

文字列の書式化が簡単になった。

var message = $"ファイル {path} が存在しません。";

以前の書き方

string.Format を使う必要があった。
var message = string.Format("ファイル {0} が存在しません。", path);

例外フィルター (Exception filters)

nameof 式 (The nameof expression)

変数などの名前を文字列として取得できるようになった。

if (path == null) throw new ArgumentNullException(nameof(path));

以前の書き方

文字列で指定する必要があったため、リファクターの対象にならなかった。
if (path == null) throw new ArgumentNullException("path");

Catch ブロックと Finally ブロックでの Await (Await in Catch and Finally blocks)

インデクサーを使用して関連コレクションを初期化する (Initialize associative collections using indexers)

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2