What is the difference between lambdas and delegates in the .NET Framework?

I am asked this question a lot, and I thought that I would try to contribute to how best to describe the difference.

+51
c # lambda
Sep 16 '08 at 14:55
source share
16 answers

These are actually two different things. The delegate is actually the name of a variable containing a reference to a method or lambda, and lambda is a method without a constant name.

Lambdas are very similar to other methods, with the exception of a few subtle differences.

  • The usual method is defined in "statement" and bound to a constant name, while lambda is defined "on the fly" in "expression" and does not have a constant name.
  • Some lambdas can be used with .NET expression trees, while methods cannot.

The delegate is defined as follows:

delegate Int32 BinaryIntOp(Int32 x, Int32 y); 

A variable of type BinaryIntOp can either have a method or be assigned to labmda if the signature is the same: two Int32 arguments and an Int32 return.

Lambda can be defined as follows:

 BinaryIntOp sumOfSquares = (a, b) => a*a + b*b; 

Another thing to note is that although the generic Func and Action types are often considered "lambda types", they are similar to any other delegate. The best part is that they essentially define a name for any type of delegate you may need (up to 4 parameters, although you can certainly add more of your own). Therefore, if you use many types of delegates, but no more than once, you can avoid cluttering your code with delegate declarations using Func and Action.

Here is an illustration of how Func and Action are not just for lambda:

 Int32 DiffOfSquares(Int32 x, Int32 y) { return x*x - y*y; } Func<Int32, Int32, Int32> funcPtr = DiffOfSquares; 

Another useful thing to know is that delegate types (not methods themselves) with the same signature but with different names will not be implicitly passed to each other. This includes the delegates to Func and Action. However, if the signature is identical, you can explicitly indicate between them.

Going the Extra Mile .... In C #, the functions are flexible, using lambdas and delegates. But C # does not have "first-class features." You can use the function name assigned to the delegate variable to essentially create an object representing this function. But this is really a compiler trick. If you start an expression by writing down the name of the function, followed by a dot (i.e., try to access a member of the function itself), you will find that there are no elements for the link. Even those from Object. This prevents the programmer from doing useful (and potentially dangerous, of course) things like adding extension methods that can be called for any function. The best you can do is extend the Delegate class, which is also useful, but not so much.

Update: also see Karg's answer illustrating the difference between anonymous delegates and methods and lambdas.

Update 2: James Hart makes an important, albeit very technical, comment that lambdas and delegates are not .NET objects (i.e., the CLR does not have a delegate or lambda concept), but rather they are wireframe and language constructs.

+61
Sep 16 '08 at 15:50
source share

The question is a bit ambiguous, which explains the wide disparity in the answers you get.

You really asked what is the difference between lambdas and delegates in the .NET framework; this may be one of many factors. You're asking:

  • What is the difference between lambda expressions and anonymous delegates in C # (or VB.NET)?

  • What is the difference between System.Linq.Expressions.LambdaExpression objects and System.Delegate objects in .NET 3.5?

  • Or something somewhere in between or around these extremes?

Some people seem to be trying to give you an answer to the question: “What is the difference between C # Lambda and .NET System.Delegate expressions?”, Which doesn't make much sense.

The .NET framework itself does not understand the concept of anonymous delegates, lambda expressions or closures - all this is determined by the language specifications. Think about how the C # compiler translates the definition of an anonymous method into a method of a generated class with member variables to preserve the closing state; to .NET, there is nothing anonymous about the delegate; it's just anonymous to the C # programmer writing it. This applies equally to the lambda expression assigned to the delegate type.

What .NET understands is the delegate’s idea - a type that describes the signature of a method, instances of which are related calls to specific methods for specific objects or unrelated calls to a specific method for a specific type that can be called against any object of that type where specified the method corresponds to the specified signature. Such types are all inherited from System.Delegate.

.NET 3.5 also introduces the System.Linq.Expressions namespace, which contains classes for describing code expressions, and which can also be related or unconnected method calls for specific types or objects. LambdaExpression instances can then be compiled into actual delegates (as a result of which a dynamic method based on the structure of the expression is encoded and a delegate pointer is returned).

In C #, you can instantiate types of System.Expressions.Expression types by assigning a lambda expression to a variable of the specified type, which will generate the appropriate code to build the expression at run time.

Of course, if you asked what is the difference between lambda expressions and anonymous methods in C #, after all, then all this is quite a lot, and in this case the main difference is brevity, which relies on anonymous delegates when you don't care about parameters and do not plan to return a value, but towards lambdas, when you want to enter type parameters and return types.

And lambda expressions support generation expression.

+23
Sep 16 '08 at 16:48
source share

One difference is that an anonymous delegate can omit the parameters, while the lambda must match the exact signature. Given:

 public delegate string TestDelegate(int i); public void Test(TestDelegate d) {} 

you can call it in the following four ways (note that the second line has an anonymous delegate that has no parameters):

 Test(delegate(int i) { return String.Empty; }); Test(delegate { return String.Empty; }); Test(i => String.Empty); Test(D); private string D(int i) { return String.Empty; } 

You cannot pass to a lambda expression that has no parameters or a method that has no parameters. They are not allowed:

 Test(() => String.Empty); //Not allowed, lambda must match signature Test(D2); //Not allowed, method must match signature private string D2() { return String.Empty; } 
+14
Sep 16 '08 at 15:16
source share

Delegates are equivalent to pointers to pointers / method pointers / callbacks (choose), and lambdas are significantly simplified anonymous functions. At least what I say to people.

+12
Sep 16 '08 at 14:57
source share

I don't have much experience with this, but the way I would describe it is that the delegate is a wrapper around any function, while the lambda expression itself is an anonymous function.

+3
Sep 16 '08 at 14:57
source share

A delegate is always basically a pointer to a function. A lambda can turn into a delegate, but it can also turn into a LINQ expression tree. For example,

 Func<int, int> f = x => x + 1; Expression<Func<int, int>> exprTree = x => x + 1; 

The first line creates a delegate, and the second creates an expression tree.

+3
Sep 16 '08 at 15:07
source share

lambdas is just syntactic sugar on the delegate. The compiler completes the conversion of lambdas to delegates.

This is the same, I believe:

 Delegate delegate = x => "hi!"; Delegate delegate = delegate(object x) { return "hi";}; 
+2
Sep 16 '08 at 14:58
source share

The delegate is the signature of the function; something like

 delegate string MyDelegate(int param1); 

The delegate does not implement the body.

A lambda is a function call that matches the signature of the delegate. For the above delegate, you can use any of:

 (int i) => i.ToString(); (int i) => "ignored i"; (int i) => "Step " + i.ToString() + " of 10"; 

The Delegate type is poorly named; creating an object of type Delegate actually creates a variable that can contain functions — be it lambda, static methods, or class methods.

+2
Sep 16 '08 at 15:02
source share

A delegate is a reference to a method with a specific list of parameters and a return type. It may or may not include an object.

A lambda expression is a form of anonymous function.

+2
Sep 16 '08 at 16:34
source share

It is pretty clear that the question was to be "what is the difference between lambdas and anonymous delegates?" Of all the answers here, only one person understood this correctly - the main difference is that lambdas can be used to create expression trees, as well as for delegates.

You can learn more about MSDN: http://msdn.microsoft.com/en-us/library/bb397687.aspx

+2
Jun 23 '11 at 20:18
source share

Delegates are really structural typing for functions. You can do the same with nominal typing and implement an anonymous class that implements an interface or an abstract class, but in the end it is a lot of code when only one function is needed.

Lambda comes from the idea of ​​lambda calculus of the Alonso Church in the 1930s. This is an anonymous way to create functions. They become especially useful for composing functions.

So, although some may say that lambda is syntactic sugar for delegates, I would say that delegates are a bridge to make people easier in lambdas in C #.

+1
Sep 16 '08 at 15:10
source share

A delegate is a queue of function pointers; calling a delegate can call several methods. A lambda is essentially an anonymous method declaration, which can be interpreted by the compiler differently, depending on what context it is used like.

You can get a delegate that points to the lambda expression as a method by passing it to the delegate or passing it as a parameter to a method that expects a specific type of delegation that the compiler will do for you. Using it inside the LINQ statement, the lambda will be translated by the compiler into the expression tree instead of a simple delegate.

The difference is that lambda is a complicated way to define a method inside another expression, and a delegate is the actual type of the object.

+1
Sep 16 '08 at 16:36
source share

Lambdas are simplified versions of delegates. They have some closure properties like anonymous delegates, but also allow the use of implicit typing. Lambda like:

 something.Sort((x, y) => return x.CompareTo(y)); 

much more concise than what you can do with the delegate:

 something.Sort(sortMethod); ... private int sortMethod(SomeType one, SomeType two) { one.CompareTo(two) } 
0
Sep 16 '08 at 15:13
source share

Here is an example I pretended to be a bit on my lame blog. Suppose you wanted to update a shortcut from a workflow. I have 4 examples of updating this shortcut from 1 to 50 using delegates, anonymous delegates, and 2 lambda types.

  private void button2_Click(object sender, EventArgs e) { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(worker_DoWork); worker.RunWorkerAsync(); } private delegate void UpdateProgDelegate(int count); private void UpdateText(int count) { if (this.lblTest.InvokeRequired) { UpdateProgDelegate updateCallBack = new UpdateProgDelegate(UpdateText); this.Invoke(updateCallBack, new object[] { count }); } else { lblTest.Text = count.ToString(); } } void worker_DoWork(object sender, DoWorkEventArgs e) { /* Old Skool delegate usage. See above for delegate and method definitions */ for (int i = 0; i < 50; i++) { UpdateText(i); Thread.Sleep(50); } // Anonymous Method for (int i = 0; i < 50; i++) { lblTest.Invoke((MethodInvoker)(delegate() { lblTest.Text = i.ToString(); })); Thread.Sleep(50); } /* Lambda using the new Func delegate. This lets us take in an int and * return a string. The last parameter is the return type. so * So Func<int, string, double> would take in an int and a string * and return a double. count is our int parameter.*/ Func<int, string> UpdateProgress = (count) => lblTest.Text = count.ToString(); for (int i = 0; i < 50; i++) { lblTest.Invoke(UpdateProgress, i); Thread.Sleep(50); } /* Finally we have a totally inline Lambda using the Action delegate * Action is more or less the same as Func but it returns void. We could * use it with parameters if we wanted to like this: * Action<string> UpdateProgress = (count) => lblT…*/ for (int i = 0; i < 50; i++) { lblTest.Invoke((Action)(() => lblTest.Text = i.ToString())); Thread.Sleep(50); } } 
0
Sep 16 '08 at 16:12
source share

I assume that your question is about C #, not .NET, because of the ambiguity of your question, since .NET does not get lonely - that is, without C # - understanding delegates and lambda expressions.

A (normal, as opposed to the so-called common delegates, cf later), the delegate should be considered as a kind of C ++ typedef type of function pointer, for example, in C ++:

 R (*thefunctionpointer) ( T ) ; 

typedef type thefunctionpointer , which is a type of function pointer that takes an object of type T and returns an object of type R You would use it as follows:

 thefunctionpointer = &thefunction ; R r = (*thefunctionpointer) ( t ) ; // where t is of type T 

where thefunction will be a function that takes T and returns R

In C # you will go for

 delegate R thedelegate( T t ) ; // and yes, here the identifier t is needed 

and you will use it as follows:

 thedelegate thedel = thefunction ; R r = thedel ( t ) ; // where t is of type T 

where thefunction will be a function that takes T and returns R This is for delegates, the so-called normal delegates.

Now you also have common delegates in C # that are delegates that are common, that is, "templates", so to speak, using a C ++ expression. They are defined as follows:

 public delegate TResult Func<in T, out TResult>(T arg); 

And you can use them as follows:

 Func<double, double> thefunctor = thefunction2; // call it a functor because it is // really as a functor that you should // "see" it double y = thefunctor(2.0); 

where thefunction2 is a function that takes as an argument and returns a double .

Now imagine that instead of thefunction2 I would like to use a “function”, which is not yet defined, using an instruction, and that I will never use it later. Then C # allows you to use the expression of this function. By expression I mean the expression "mathematical" (or functional to stick with programs), for example: before double x I will contact double x*x . In math, you write this using the "\ mapsto" latex character . Functional notation was written in C #: => . For example:

 Func<double, double> thefunctor = ( (double x) => x * x ); // outer brackets are not // mandatory 

(double x) => x * x is expression . This is not a type, while delegates (general or not).

Morality? After all, what is a delegate (or generic delegate) if not a function pointer type (e.g. wrapped + smart + generic function pointer type), yes? Something other! See this and which .
0
Nov 21 '14 at 11:10
source share

Well, the really simplified version is that lambda is just a shorthand for an anonymous function. A delegate can do much more than just anonymous functions: things like events, asynchronous calls, and a few chains of methods.

-one
Sep 16 '08 at 14:56
source share



All Articles