LoginSignup
1
1

More than 5 years have passed since last update.

メソッドをラムダ式で簡略化しよう(メモ)

Last updated at Posted at 2017-09-17

メソッドとラムダ

デリゲートだけでなく、メソッドもラムダ式で書くことが出来る。(C#6.0より)
但し、ラムダ演算子の右側が式の場合に限る。文は不可。
以下に例を示す。

mlambda.cs
using System;

class Program
{
    public static int Add(int num1, int num2) => num1 + num2;
}

勿論、エントリポイント(Main)もラムダ式で記述することが出来る。
先ほどの続きから。

mlamda.cs
    public static void Main(string[] args) => Console.WriteLine(Add(10, 20));

綺麗に簡略化できるけど、あまり使いすぎるのも良くない。

追記:プロパティ、インデクサとラムダ

プロパティ、インデクサもラムダ式で簡略化できる。
但し、getterのみとなる。
プロパティの例を示す。

plamda.cs
public int Num => 10;

インデクサも同じような感じに書ける。
やっぱり需要としてはメソッドが高そう。

1
1
2

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
1