クイックリファレンス

C# 7.0 新機能 チートシート

C# 7.0 のクイックリファレンス:out 変数、パターンマッチング、タプルと分解、ローカル関数、ref 戻り値、数値区切り文字、式形式メンバー。

· 公開日

C# 7.0 (.NET Framework 4.7 / .NET Core 2.0) で導入された構文と機能のクイックリファレンス。

out 変数宣言

メソッド呼び出しの引数リスト内で直接 out 変数を宣言できます:

// C# 7 以前:
int result;
if (int.TryParse(input, out result)) { ... }

// C# 7 以降:
if (int.TryParse(input, out int result))
{
    Console.WriteLine($"Parsed number: {result}");
}

// 不要な out パラメータを _ で破棄
if (int.TryParse(input, out _))
{
    Console.WriteLine("Input is valid numeric");
}

パターンマッチング (Pattern Matching)

is 式による型パターン

public void PrintArea(object shape)
{
    if (shape is Circle c)
    {
        Console.WriteLine($"Circle area: {Math.PI * c.Radius * c.Radius}");
    }
    else if (shape is Rectangle r)
    {
        Console.WriteLine($"Rectangle area: {r.Width * r.Height}");
    }
}

パターンと when 句を備えた Switch 文

switch (shape)
{
    case Circle c:
        Console.WriteLine($"Circle with radius {c.Radius}");
        break;
    case Rectangle r when r.Width == r.Height:
        Console.WriteLine($"Square {r.Width} x {r.Height}");
        break;
    case Rectangle r:
        Console.WriteLine($"Rectangle {r.Width} x {r.Height}");
        break;
    case null:
        throw new ArgumentNullException(nameof(shape));
    default:
        Console.WriteLine("Unknown shape");
        break;
}

タプルと分解 (Tuples & Deconstruction)

古いターゲットでは System.ValueTuple パッケージが必要です:

名前付きタプルの戻り値

(string First, string Last, int Age) GetUser()
{
    return ("Alice", "Smith", 30);
}

var user = GetUser();
Console.WriteLine($"{user.First} is {user.Age} years old");

タプルの分解

// 個別の変数へ分解
var (first, last, age) = GetUser();

// または既存の変数へ代入
string f, l;
int a;
(f, l, a) = GetUser();

ローカル関数 (Local Functions)

親関数のスコープ内にネストしたヘルパーメソッドを宣言できます:

public int Factorial(int n)
{
    if (n < 0) throw new ArgumentException("Negative value", nameof(n));
    return Calculate(n);

    int Calculate(int x)
    {
        return x <= 1 ? 1 : x * Calculate(x - 1);
    }
}

リテラルの強化

// 桁区切り文字 (_)
int million = 1_000_000;
long hexMask = 0xFF_EC_00_12;

// 2進数リテラル (0b)
byte byteFlag = 0b1010_0110;

ref ローカル変数と参照戻り値

値のコピーではなく、メモリ格納場所への参照を返します:

public ref int Find(int target, int[] numbers)
{
    for (int i = 0; i < numbers.Length; i++)
    {
        if (numbers[i] == target) return ref numbers[i];
    }
    throw new IndexOutOfRangeException();
}

int[] array = { 10, 20, 30 };
ref int val = ref Find(20, array);
val = 99; // array[1] becomes 99

式形式のメンバー (Expression-Bodied Members)

コンストラクタ、ファイナライザ、プロパティアクセサへ式形式構文が拡張されました:

class Item
{
    private string _name;

    // Expression-bodied constructor
    public Item(string name) => _name = name ?? throw new ArgumentNullException(nameof(name));

    // Expression-bodied property accessor
    public string Name
    {
        get => _name;
        set => _name = value ?? "default";
    }
}

関連テーマ