[C # 3.0 Getting Started] [Chapter One lambda expressions] section III: The difference between a lambda and an anonymous method

Source: Internet
Author: User
Tags anonymous comparison

The difference between a lambda expression and an anonymous method

So why is a lambda expression shorter than an anonymous method? Does this kind of magic trick really work? Are there any important information missing? To answer these questions, let's compare the anonymous method with the lambda expression to see how the lambda expression is written.

1using System;
2
3delegate int SampleDelegate(int x, int y);
4
5class Program
6{
7  private static void Calculate(int x, int y, SampleDelegate calculator)
8  {
9    Console.WriteLine(calculator(x, y));
10  }
11
12  static void Main(string[] args)
13  {
14    // 匿名方法
15    Calculate(1, 2,
16      delegate(int x, int y) { return x + y; }); // 输出:3
17
18    // Lambda表达式
19    Calculate(1, 2, (x, y) => x + y); // 输出:3
20  }
21}
22

Comparison of List9 anonymous method and lambda expression

In this code, the following sections are written as anonymous methods and lambda expressions:

anonymous method

delegate (int x, int y) {return x + y;}

Lambda expression

(x, y) => x + y

A literal comparison will reveal the following differences:

* Delegate keyword is gone

* The return keyword is gone

* Specifies the type of the parameter int is gone

* The bracket "{}" is not

* The semicolon at the end of the line ";" Without

* NEW "=>" two characters appear

Below, for these differences, one to explain.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.