0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C# > Visual Studio 2017 RC 型スイッチを試してみた

0
Last updated at Posted at 2016-11-19

ついにVisual Studio 2017 RCがリリースされた。
この記事では型スイッチについて試してみたことを述べる。

環境

Visual Studio 2017 RC

試してみたこと

ユーザーが入力した文字列をParseし、intであればそれをint型変数に代入する。
そうでなければintでない旨のメッセージを表示する。

Program.cs
using System;

namespace ConsoleTestPetternMatch
{
    class Program
    {
        static void Main(string[] args)
        {
            string s;
            while((s = Console.ReadLine()) != "")
            {
                // C#6までの書き方
                int n1 = 0;
                if (int.TryParse(s, out n1))
                {
                    Console.WriteLine($"入力した数字は{n1}です。");
                }
                else
                {
                    Console.WriteLine($"数字ではありません");
                }

                // C#7ではパターンマッチングと拡張メソッドでこのように書ける
                if (s.Parse() is int n2)
                {
                    Console.WriteLine($"入力した数字は{n2}です。");
                }
                else
                {
                    Console.WriteLine($"数字ではありません");
                }
            }
        }
    }

    static class StringExtension
    {
        public static int? Parse(this string s)
        {
            int n;
            return int.TryParse(s, out n) ? (int?)n : null;
        }
    }
}

参考にしたサイト

型スイッチ
次期C# 7: 式の新機能 ― throw式&never型/式形式のswitch(match式)/宣言式/シーケンス式

思ったこと

  • 型スイッチはis演算子による型の調査と型宣言を同時に行えるところが便利!
  • 型スイッチとは直接関係ないが宣言式が未だに実装されてないのが不便!

宣言式について

宣言式とは「変数を宣言すると同時に変数の値をそのまま返す」ものである。
例えば

Program.cs
            string s;
            while((s = Console.ReadLine()) != "")
            {
            }

と書いているところを

Program.cs
            while((string s = Console.ReadLine()) != "")
            {
            }

のように書けるのである。つまり、(string s = Console.ReadLine())が式として評価され、その評価結果としてsの値が使えるのである。

未だに残る違和感

私はC++の経験があるのでこのような書き方に慣れていたが、C#では実装されていない事に違和感を感じている。

for(int i = 0; i < 10; i++)のようにfor文では宣言できるのに、while文ではなぜ宣言できないのか?
そういう意味ではif文もif((string s = Console.ReadLine()) != "")のように書けないのだが、型スイッチの導入により幾分緩和された気はする。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?