やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

C#の概念 パターンマッチ

 is句やswitch文を使う。

成果物

コード

is

C#6.0

if (shape is Square)
{
    var s = (Square)shape;
    return s.Side * s.Side;
} 

C#7.0

if (shape is Square s)
    return s.Side * s.Side;

 is句に変数名を追加することで、その変数は指定した型へキャスト済みの値となる。

switch

public static double CalcArea(object shape)
{
    switch (shape)
    {
        case Square s:
            return s.Side * s.Side;
        case Circle c:
            return c.Radius * c.Radius * Math.PI;
        case Rectangle r:
            return r.Height * r.Length;
        default:
            throw new ArgumentException(
                message: "shape is not a recognized shape",
                paramName: nameof(shape));
    }
}

 switch文にオブジェクトを指定できるようになった。

when句

public static double ComputeArea_Version3(object shape)
{
    switch (shape)
    {
        case Square s when s.Side == 0:
        case Circle c when c.Radius == 0:
            return 0;

        case Square s:
            return s.Side * s.Side;
        case Circle c:
            return c.Radius * c.Radius * Math.PI;
        default:
            throw new ArgumentException(
                message: "shape is not a recognized shape",
                paramName: nameof(shape));
    }
}

 when句を使えば条件指定できる。

 caseにはnullも使える。

        case null:
            throw new ArgumentNullException(paramName: nameof(shape), message: "Shape must not be null");

 varを使って複雑な条件にもできる。

        case var o when (o?.Trim().Length ?? 0) == 0:
            // white space
            return null;

対象環境

$ uname -a
Linux raspberrypi 4.19.75-v7l+ #1270 SMP Tue Sep 24 18:51:41 BST 2019 armv7l GNU/Linux