8

1:

Func<int, int> myFunc = new Func<int,int>(delegate(int x) {
    return x + 1;
});

2:

Func<int, int> myFunc = delegate(int x) {
    return x + 1;
};

3:

Func<int, int> myFunc = x => x + 1;

What is the difference between them?

nawfal
  • 70,104
  • 56
  • 326
  • 368
  • duplicate of [delegate keyword vs. lambda notation](http://stackoverflow.com/questions/208381/whats-the-difference-between-anonymous-methods-c-2-0-and-lambda-expressions) and [What is the difference between new Action() and a lambda?](http://stackoverflow.com/questions/765966/what-is-the-difference-between-new-action-and-a-lambda) – nawfal Jul 06 '14 at 20:48

2 Answers2

8

They are all the same - just syntactic sugar that compiles to the same thing.

That is - with type inference and other compiler goodies, 3 is just a very very short way to say 1.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • So what is the difference between anonymous function and Func? Are they same? –  Feb 23 '13 at 15:10
  • @Lior - `Func` is a defined delegate. An anonymous function does not have a named delegate type. – Oded Feb 23 '13 at 15:12
  • @Lior , Yes they are same at runtime but there is difference in how you define them for making compiler understand that its a delegate which accepts these many specific type of parameters and return a specific type. – Somnath Feb 23 '13 at 15:21
7

They're all the same. The first two are examples of anonymous methods. The last is an example of a lambda expression. Anonymous methods and lambda expressions are collectively called anonymous functions.

Anonymous methods were introduced in C# 2; lambda expressions were introduced in C# 3 and mostly superseded anonymous methods. Note that lambda expressions can also be converted to expression trees which represent the code as data rather than IL, as well as delegates.

Note that Func<TResult>, Func<T, TResult> etc are just examples of delegate types. You can convert anonymous functions to any compatible delegate type. For example:

public delegate int Foo(string x);

Foo foo = text => text.Length;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • So what is the difference between anonymous function and Func? Are they same? –  Feb 23 '13 at 15:11
  • @Lior: `Func` is just the name of a delegate type. – Jon Skeet Feb 23 '13 at 15:12
  • I do not like the choice of terminology by spec team regarding "anonymous method" and "anonymous function". Should have been other way around. In C# there is named "method". Its anonymous cousin should be then anonymous "method", but they chose to call it "anonymous function". Doesn't look good. Also the current anonymous method that looks like `(int i) { return i; }` sounds so familiar with mathematical concept of functions, hence "anonymous function" should have fit there better :( – nawfal Jul 06 '14 at 21:23