C# ラムダ式の簡単な使い方

  • 作成日 2020.10.06
  • 更新日 2022.03.04
  • C#
C# ラムダ式の簡単な使い方

C#でdelegateをより簡潔に利用できるラムダ式の簡単な使い方を記述してます。

環境

  • OS windows10 pro 64bit
  • Microsoft Visual Studio Community 2019 Version 16.7.1

基本的な使い方

ラムダ式を使用すると、delegete宣言を省略することができ、なおかつ処理が1行の場合、returnすらも省略することができます。

以下のコードは、定義済みデリゲートである「Action」と「Func」と「ラムダ式」を使用したサンプルとなります。

Action : 戻り値なしで使用
Func : 戻り値ありで使用

using System;

namespace testapp
{

    class Program
    {
        static void Main(string[] args)
        {
            // 引数 なし 戻り値 なし
            Action action1 = () => { Console.WriteLine("hello World"); };
            action1();

            // 引数 あり 戻り値 なし
            Action<string> action2 = (msg) => { Console.WriteLine(msg); };
            action2("hello world");

            // 引数 複数 戻り値 なし
            Action<string, string, string> action3 = (msg1,msg2,msg3) => { Console.WriteLine(msg1 + msg2 + msg3); };
            action3("hello", "world","!!");

            // 引数 なし 戻り値 あり
            Func<int> func1 = () => { return 10; };
            Console.WriteLine(func1());

            // 引数 あり 戻り値 あり
            Func<int, int> func2 = (x) => x * 2; ;
            Console.WriteLine(func2(2));

            // 引数 複数 戻り値 あり
            Func<int, int, int> func3 = (x,y) => x * y;
            Console.WriteLine(func3(2,3));

        }

    }
}

実行結果