user1735111
user1735111

Reputation:

Difference between various ways of instantiating a delegate (Func<T, T>)?

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?

Upvotes: 8

Views: 3242

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500525

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;

Upvotes: 7

Oded
Oded

Reputation: 499002

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.

Upvotes: 8

Related Questions