delegate keyword vs. lambda notation - c#

Once it is compiled, is there a difference between:
delegate { x = 0; }
and
() => { x = 0 }
?

Short answer : no.
Longer answer that may not be relevant:
If you assign the lambda to a delegate type (such as Func or Action) you'll get an anonymous delegate.
If you assign the lambda to an Expression type, you'll get an expression tree instead of a anonymous delegate. The expression tree can then be compiled to an anonymous delegate.
Edit:
Here's some links for Expressions.
System.Linq.Expression.Expression(TDelegate) (start here).
Linq in-memory with delegates (such as System.Func) uses System.Linq.Enumerable. Linq to SQL (and anything else) with expressions uses System.Linq.Queryable. Check out the parameters on those methods.
An Explanation from ScottGu. In a nutshell, Linq in-memory will produce some anonymous methods to resolve your query. Linq to SQL will produce an expression tree that represents the query and then translate that tree into T-SQL. Linq to Entities will produce an expression tree that represents the query and then translate that tree into platform appropriate SQL.

I like Amy's answer, but I thought I'd be pedantic. The question says, "Once it is compiled" - which suggests that both expressions have been compiled. How could they both compile, but with one being converted to a delegate and one to an expression tree? It's a tricky one - you have to use another feature of anonymous methods; the only one which isn't shared by lambda expressions. If you specify an anonymous method without specifying a parameter list at all it is compatible with any delegate type returning void and without any out parameters. Armed with this knowledge, we should be able to construct two overloads to make the expressions completely unambiguous but very different.
But disaster strikes! At least with C# 3.0, you can't convert a lambda expression with a block body into an expression - nor can you convert a lambda expression with an assignment in the body (even if it is used as the return value). This may change with C# 4.0 and .NET 4.0, which allow more to be expressed in an expression tree. So in other words, with the examples MojoFilter happened to give, the two will almost always be converted to the same thing. (More details in a minute.)
We can use the delegate parameters trick if we change the bodies a little bit though:
using System;
using System.Linq.Expressions;
public class Test
{
static void Main()
{
int x = 0;
Foo( () => x );
Foo( delegate { return x; } );
}
static void Foo(Func<int, int> action)
{
Console.WriteLine("I suspect the anonymous method...");
}
static void Foo(Expression<Func<int>> func)
{
Console.WriteLine("I suspect the lambda expression...");
}
}
But wait! We can differentiate between the two even without using expression trees, if we're cunning enough. The example below uses the overload resolution rules (and the anonymous delegate matching trick)...
using System;
using System.Linq.Expressions;
public class Base
{
public void Foo(Action action)
{
Console.WriteLine("I suspect the lambda expression...");
}
}
public class Derived : Base
{
public void Foo(Action<int> action)
{
Console.WriteLine("I suspect the anonymous method...");
}
}
class Test
{
static void Main()
{
Derived d = new Derived();
int x = 0;
d.Foo( () => { x = 0; } );
d.Foo( delegate { x = 0; } );
}
}
Ouch. Remember kids, every time you overload a method inherited from a base class, a little kitten starts crying.

In the two examples above there's no difference, zero.
The expression:
() => { x = 0 }
is a Lambda expression with statement body, so it can't be compiled as an expression tree. In fact it doesn't even compile because it needs a semicolon after 0:
() => { x = 0; } // Lambda statement body
() => x = 0 // Lambda expression body, could be an expression tree.

Amy B is correct. Note that there can be advantages to using expression trees. LINQ to SQL will examine the expression tree and convert it to SQL.
You can also play tricks with lamdas and expression trees to effectively pass the names of class members to a framework in a refactoring-safe way. Moq is an example of this.

There is a difference
Example:
var mytask = Task.Factory.StartNew(() =>
{
Thread.Sleep(5000);
return 2712;
});
mytask.ContinueWith(delegate
{
_backgroundTask.ContinueTask(() =>lblPercent.Content = mytask.Result.ToString(CultureInfo.InvariantCulture));
});
And I replace with lambda:(error)
var mytask = Task.Factory.StartNew(() =>
{
Thread.Sleep(5000);
return 2712;
});
mytask.ContinueWith(()=>
{
_backgroundTask.ContinueTask(() =>lblPercent.Content = mytask.Result.ToString(CultureInfo.InvariantCulture));
});

Some basics here.
This is a anonymous method
(string testString) => { Console.WriteLine(testString); };
As anonymous methods do not have names we need a delegate in which we can assign both of these methods or expressions. e.g.
delegate void PrintTestString(string testString); // declare a delegate
PrintTestString print = (string testString) => { Console.WriteLine(testString); };
print();
Same with the lambda expression. Usually we need a delegate to use them
s => s.Age > someValue && s.Age < someValue // will return true/false
We can use a func delegate to use this expression.
Func< Student,bool> checkStudentAge = s => s.Age > someValue && s.Age < someValue ;
bool result = checkStudentAge ( Student Object);

Related

Is there a difference between C# lambda functions with brackets vs no brackets? [duplicate]

Fundamentally, is there any difference between a single-line expression lambda and a statement lambda? Take the following code, for example:
private delegate void MyDelegate();
protected static void Main()
{
MyDelegate myDelegate1 = () => Console.WriteLine("Test 1");
MyDelegate myDelegate2 = () => { Console.WriteLine("Test 2"); };
myDelegate1();
myDelegate2();
Console.ReadKey();
}
While I prefer the first because I find the brackets to be ugly, is there anything different between the two (besides the obvious part about requiring brackets for multi-line statements)?
You need statement lambda for multistatement lambdas. In addition statement lambdas are not supported by expression providers like LINQ to SQL. Before .NET 4.0 the .NET Framework did not have support for statement expression trees. This was added in 4.0 but as far as I know no provider uses it.
Action myDelegate1 = () => Console.WriteLine("Test 1");
Expression<Action> myExpression = () => { Console.WriteLine("Test 2") }; //compile error unless you remove the { }
myDelegate1();
Action myDelegate2 = myExpression.Compile();
myDelegate2();
Otherwise they are the same.
Reflector to the rescue! The disassembled code looks like this:
private static void Main(string[] args)
{
MyDelegate myDelegate1 = delegate {
Console.WriteLine("Test 1");
};
MyDelegate myDelegate2 = delegate {
Console.WriteLine("Test 2");
};
myDelegate1();
myDelegate2();
Console.ReadKey();
}
So no, there is no real difference between the two. Be happy.
The two are the same - the first is syntactic sugar to the second and both will compile to the same IL.
No, there is no difference in this example. If the body of the lambda is only one expression, you can drop the brackets. However, once the lambda contains more than one expression, like so:
MyDelegate myDelegate2 = () => {
Console.WriteLine("Test 2");
Console.WriteLine("Test 2");
};
the brackets are mandatory.
If the delegate returns a value, return is necessary in statement lambda as follows.
Func<int, int, bool> foo = (x, y) => { return x == y; };
Func<int, int, bool> goo = (x, y) => x == y;
Personnaly, i prefer the Lambda Expression. The Expression have a value where the Statement does not.
i think the following links can help you :
http://lambda-the-ultimate.org/node/1044
Same for the OP example, but after C# 6.0, allowing you to use same expression syntax to define normal non-lambda methods within a class. For example:
public static double AreaOfTriangle(double itsbase, double itsheight)
{
return itsbase * itsheight / 2;
}
The above code snippet can be written only if the method can be turned into a single expression. In short, it can be used the expression lambda syntax, but not the statement lambda syntax.
public static double
AreaOfTrianglex(double itsbase, double itsheight) => itsbase * itsheight / 2;
From the docs (https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions):
Statement lambdas, like anonymous methods, cannot be used to create expression trees.

Calling a void-parameter lambda gives compiler error

From this question: Lambda expression with a void input
I have the following very simple code:
int minutes = () => 9;
I get compiler error:
Cannot convert lambda expression to type 'int' because it is not a
delegate type
I've found several questions about this error but they're all about more specific issues. I actually want to give my lambda a body but thought I'd start simple first to check my syntax:
//I know this is a weird example
int minutes = ()=> { if(x==9) return 9; else return 5;}
From C# guide
A lambda expression is a block of code (an expression or a statement block) that is treated as an object. It can be passed as an argument to methods, and it can also be returned by method calls.
...
Lambda expressions are code that can be represented either as a delegate, or as an expression tree that compiles to a delegate.
That means lambda expression can be represented and can represent different things: delegate or expression tree.
Your expression
() => 9;
can be so many different things, as example
public class C {
delegate int IntDelegate();
public void M() {
Func<int> minutes = () => 9;
IntDelegate minutes2 = () => 9;
Expression<Func<int>> minutesExpression = () => 9;
Expression<IntDelegate> minutesExpression2 = () => 9;
}
}
So what do you want to use?
By the way, because of all that, you can't use var with them.
And you can see how c# compiler work under the hood for different lambda here-> lambda as delegate and expression tree

Compiler Error for Expression/Func overloads

The screenshot says it pretty much.
I have the overloads as seen in the screenshot. When using a string as second parameter the compiler should figure out that the first argument can only be a Func and not an expression.
But the compiler throws an error saying 'A lamda expression with a statement body cannot be converted to an expression tree'.
Why can't the compiler figure out the correct overload?
Explicit cast does not help. What works is when i make a local variable of type Func and then use this instead.
The framework used is FakeItEasy 1.24.0
EDIT:
Here is the code that shows the behavior:
public static void Main(string[] args)
{
//compiler error
A.CallTo(() => Main(A<string[]>.That.Matches(strings =>
{
return true;
}, "description")));
//compiles
Func<string[], bool> predicate = strings =>
{
return true;
};
A.CallTo(() => Main(A<string[]>.That.Matches(predicate, "description")));
Console.ReadLine();
}
The issue is not in the call to Matches. It's in the call to CallTo, which expects an Expression<Action>.
Apparently an Expression not only can't be a lambda expression with a statement body, it also can't contain a lambda expression with a statement body.
(I'm not sure whether your "put the lambda in a local variable" solution will work or whether it just tricks the compiler and will fail at runtime.)
Here's the test I put together:
static void Overloaded(Action a, string param) { }
static void Overloaded(Expression<Action> e) { }
static void CallToAction(Action a) { }
static void CallToExprAc(Expression<Action> a) { }
static void Main(string[] args)
{
// Works
CallToAction(() => Overloaded(() => { int i = 5; }, "hi"));
// Doesn't work - using the Expression overload
CallToAction(() => Overloaded(() => { int i = 5; }));
// Doesn't work - wrapped in an outer Expression
CallToExprAc(() => Overloaded(() => { int i = 5; }, "hi"));
}
Whether your "put the expression-bodied lambda in a local" works is up to how FakeItEasy is implemented. I suspect it'll work here, but something similar in e.g. LINQ-to-SQL wouldn't - it'd just fail at runtime rather than at compile time.
I'm not sure whether this is a compiler bug, a spec bug or desirable behaviour. In section 6.5 of the C# spec we have
Certain lambda expressions cannot be converted to expression tree types: Even though the conversion exists, it fails at compile-time. This is the case if the lambda expression:
• Has a block body
• Contains simple or compound assignment operators
• Contains a dynamically bound expression
• Is async
which doesn't say "contains a lambda expression that cannot be converted to an expression tree type".

Function composition

Below a Compose function. If f and g are unary functions which return values, then Compose(f,g) returns a function which when called on x performs the equivalent to f(g(x)).
static Func<X, Z> Compose<Z, Y, X>(Func<Y, Z> f,Func<X, Y> g)
{ return x => f(g(x)); }
Here's a couple of simple Func values which can be composed:
Func<int, bool> is_zero = x => { return x == 0; };
Func<int, int> mod_by_2 = x => { return x % 2; };
E.g. this works:
Console.WriteLine(Compose(is_zero, mod_by_2)(4));
However, if I instead have these equivalent static methods:
static bool IsZero(int n) { return n == 0; }
static int ModBy2(int n) { return n % 2; }
the same example doesn't work with those. I.e. this produces a compile time error:
Console.WriteLine(Compose(IsZero, ModBy2)(4));
Explicitly passing types to Compose fixes the issue:
Console.WriteLine(Compose<bool, int, int>(IsZero, ModBy2)(4));
Is there anyway to write Compose such that it works on the static methods without the explicit types?
Is this a good approach to take to implementing Compose? Can anyone make improvements to this?
The problem here is not the use of static methods but the use of method groups. When you use a function name as an expression without invoking it then it's a method group and must go through method group conversion. You would have the exact same problem with instance methods.
The problem you're running into is that C# can't do return type inference on method groups. Using Compose(IsZero, ModBy2)) requires the return type to be inferred for both IsZero and ModBy2 and hence this operation fails.
This is a known limitation in the inference capabilities of the C# compiler. Eric Lippert wrote an extensive blog article on this particular subject which covers this problem in detail
http://blogs.msdn.com/b/ericlippert/archive/2007/11/05/c-3-0-return-type-inference-does-not-work-on-member-groups.aspx

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

I get asked this question a lot and I thought I'd solicit some input on how to best describe the difference.
They are actually two very different things. "Delegate" is actually the name for a variable that holds a reference to a method or a lambda, and a lambda is a method without a permanent name.
Lambdas are very much like other methods, except for a couple subtle differences.
A normal method is defined in a "statement" and tied to a permanent name, whereas a lambda is defined "on the fly" in an "expression" and has no permanent name.
Some lambdas can be used with .NET expression trees, whereas methods cannot.
A delegate is defined like this:
delegate Int32 BinaryIntOp(Int32 x, Int32 y);
A variable of type BinaryIntOp can have either a method or a labmda assigned to it, as long as the signature is the same: two Int32 arguments, and an Int32 return.
A lambda might be defined like this:
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 just like any other delegates. The nice thing about them is that they essentially define a name for any type of delegate you might need (up to 4 parameters, though you can certainly add more of your own). So if you are using a wide variety of delegate types, but none more than once, you can avoid cluttering your code with delegate declarations by using Func and Action.
Here is an illustration of how Func and Action are "not just for lambdas":
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 different names will not be implicitly casted to each other. This includes the Func and Action delegates. However if the signature is identical, you can explicitly cast between them.
Going the extra mile.... In C# functions are flexible, with the use of lambdas and delegates. But C# does not have "first-class functions". You can use a function's name assigned to a delegate variable to essentially create an object representing that function. But it's really a compiler trick. If you start a statement by writing the function name followed by a dot (i.e. try to do member access on the function itself) you'll find there are no members there to reference. Not even the ones from Object. This prevents the programmer from doing useful (and potentially dangerous of course) things such as adding extension methods that can be called on any function. The best you can do is extend the Delegate class itself, which is surely also useful, but not quite as much.
Update: Also see Karg's answer illustrating the difference between anonymous delegates vs. methods & lambdas.
Update 2: James Hart makes an important, though very technical, note that lambdas and delegates are not .NET entities (i.e. the CLR has no concept of a delegate or lambda), but rather they are framework and language constructs.
The question is a little ambiguous, which explains the wide disparity in answers you're getting.
You actually asked what the difference is between lambdas and delegates in the .NET framework; that might be one of a number of things. Are you asking:
What is the difference between lambda expressions and anonymous delegates in the C# (or VB.NET) language?
What is the difference between System.Linq.Expressions.LambdaExpression objects and System.Delegate objects in .NET 3.5?
Or something somewhere between or around those extremes?
Some people seem to be trying to give you the answer to the question 'what is the difference between C# Lambda expressions and .NET System.Delegate?', which doesn't make a whole lot of sense.
The .NET framework does not in itself understand the concepts of anonymous delegates, lambda expressions, or closures - those are all things defined by language specifications. Think about how the C# compiler translates the definition of an anonymous method into a method on a generated class with member variables to hold closure state; to .NET, there's nothing anonymous about the delegate; it's just anonymous to the C# programmer writing it. That's equally true of a lambda expression assigned to a delegate type.
What .NET DOES understand is the idea of a delegate - a type that describes a method signature, instances of which represent either bound calls to specific methods on specific objects, or unbound calls to a particular method on a particular type that can be invoked against any object of that type, where said method adheres to the said signature. Such types all inherit from System.Delegate.
.NET 3.5 also introduces the System.Linq.Expressions namespace, which contains classes for describing code expressions - and which can also therefore represent bound or unbound calls to methods on particular types or objects. LambdaExpression instances can then be compiled into actual delegates (whereby a dynamic method based on the structure of the expression is codegenned, and a delegate pointer to it is returned).
In C# you can produce instances of System.Expressions.Expression types by assigning a lambda expression to a variable of said type, which will produce the appropriate code to construct the expression at runtime.
Of course, if you were asking what the difference is between lambda expressions and anonymous methods in C#, after all, then all this is pretty much irelevant, and in that case the primary difference is brevity, which leans towards anonymous delegates when you don't care about parameters and don't plan on returning a value, and towards lambdas when you want type inferenced parameters and return types.
And lambda expressions support expression generation.
One difference is that an anonymous delegate can omit parameters while a 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 does not have any 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 in a lambda expression that has no parameters or a method that has no parameters. These 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;
}
Delegates are equivalent to function pointers/method pointers/callbacks (take your pick), and lambdas are pretty much simplified anonymous functions. At least that's what I tell people.
A delegate is a function signature; something like
delegate string MyDelegate(int param1);
The delegate does not implement a body.
The lambda is a function call that matches the signature of the delegate. For the above delegate, you might use any of;
(int i) => i.ToString();
(int i) => "ignored i";
(int i) => "Step " + i.ToString() + " of 10";
The Delegate type is badly named, though; creating an object of type Delegate actually creates a variable which can hold functions -- be they lambdas, static methods, or class methods.
I don't have a ton of experience with this, but the way I would describe it is that a delegate is a wrapper around any function, whereas a lambda expression is itself an anonymous function.
A delegate is always just basically a function pointer. A lambda can turn into a delegate, but it can also turn into a LINQ expression tree. For instance,
Func<int, int> f = x => x + 1;
Expression<Func<int, int>> exprTree = x => x + 1;
The first line produces a delegate, while the second produces an expression tree.
Short version:
A delegate is a type that represents references to methods. C# lambda expression is a syntax to create delegates or expression trees.
Kinda long version:
Delegate is not "the name for a variable" as it's said in the accepted answer.
A delegate is a type (literally a type, if you inspect IL, it's a class) that represents references to methods (learn.microsoft.com).
This type could be initiated to associate its instance with any method with a compatible signature and return type.
namespace System
{
// define a type
public delegate TResult Func<in T, out TResult>(T arg);
}
// method with the compatible signature
public static bool IsPositive(int int32)
{
return int32 > 0;
}
// initiated and associate
Func<int, bool> isPositive = new Func<int, bool>(IsPositive);
C# 2.0 introduced a syntactic sugar, anonymous method, enabling methods to be defined inline.
Func<int, bool> isPositive = delegate(int int32)
{
return int32 > 0;
};
In C# 3.0+, the above anonymous method’s inline definition can be further simplified with lambda expression
Func<int, bool> isPositive = (int int32) =>
{
return int32 > 0;
};
C# lambda expression is a syntax to create delegates or expression trees. I believe expression trees are not the topic of this question (Jamie King about expression trees).
More could be found here.
lambdas are simply syntactic sugar on a delegate. The compiler ends up converting lambdas into delegates.
These are the same, I believe:
Delegate delegate = x => "hi!";
Delegate delegate = delegate(object x) { return "hi";};
A delegate is a reference to a method with a particular parameter list and return type. It may or may not include an object.
A lambda-expression is a form of anonymous function.
A delegate is a Queue of function pointers, invoking a delegate may invoke multiple methods. A lambda is essentially an anonymous method declaration which may be interpreted by the compiler differently, depending on what context it is used as.
You can get a delegate that points to the lambda expression as a method by casting it into a delegate, or if passing it in as a parameter to a method that expects a specific delegate type the compiler will cast it for you. Using it inside of a LINQ statement, the lambda will be translated by the compiler into an expression tree instead of simply a delegate.
The difference really is that a lambda is a terse way to define a method inside of another expression, while a delegate is an actual object type.
It is pretty clear the question was meant to be "what's the difference between lambdas and anonymous delegates?" Out of all the answers here only one person got it right - the main difference is that lambdas can be used to create expression trees as well as delegates.
You can read more on MSDN: http://msdn.microsoft.com/en-us/library/bb397687.aspx
Delegates are really just structural typing for functions. You could do the same thing with nominal typing and implementing an anonymous class that implements an interface or abstract class, but that ends up being a lot of code when only one function is needed.
Lambda comes from the idea of lambda calculus of Alonzo Church in the 1930s. It is an anonymous way of creating functions. They become especially useful for composing functions
So while some might say lambda is syntactic sugar for delegates, I would says delegates are a bridge for easing people into lambdas in c#.
Some basic here.
"Delegate" is actually the name for a variable that holds a reference to a method or a lambda
This is a anonymous method -
(string testString) => { Console.WriteLine(testString); };
As anonymous method do not have any name we need a delegate in which we can assign both of these method or expression. For Ex.
delegate void PrintTestString(string testString); // declare a delegate
PrintTestString print = (string testString) => { Console.WriteLine(testString); };
print();
Same with the lambda expression. Usually we need delegate to use them
s => s.Age > someValue && s.Age < someValue // will return true/false
We can use a func delegate to use this expression.
Func< Student,bool> checkStudentAge = s => s.Age > someValue && s.Age < someValue ;
bool result = checkStudentAge ( Student Object);
Lambdas are simplified versions of delegates. They have some of the the properties of a closure like anonymous delegates, but also allow you to use implied typing. A lambda like this:
something.Sort((x, y) => return x.CompareTo(y));
is a lot more concise than what you can do with a delegate:
something.Sort(sortMethod);
...
private int sortMethod(SomeType one, SomeType two)
{
one.CompareTo(two)
}
Heres an example I put up awhile on my lame blog. Say you wanted to update a label from a worker thread. I've got 4 examples of how to update that label from 1 to 50 using delegates, anon delegates and 2 types of lambdas.
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);
}
}
I assume that your question concerns c# and not .NET, because of the ambiguity of your question, as .NET does not get alone - that is, without c# - comprehension of delegates and lambda expressions.
A (normal, in opposition to so called generic delegates, cf later) delegate should be seen as a kind of c++ typedef of a function pointer type, for instance in c++ :
R (*thefunctionpointer) ( T ) ;
typedef's the type thefunctionpointer which is the type of pointers to a function taking an object of type T and returning an object of type R. You would use it like this :
thefunctionpointer = &thefunction ;
R r = (*thefunctionpointer) ( t ) ; // where t is of type T
where thefunction would be a function taking a T and returning an R.
In c# you would go for
delegate R thedelegate( T t ) ; // and yes, here the identifier t is needed
and you would use it like this :
thedelegate thedel = thefunction ;
R r = thedel ( t ) ; // where t is of type T
where thefunction would be a function taking a T and returning an R. This is for delegates, so called normal delegates.
Now, you also have generic delegates in c#, which are delegates that are generic, i.e. that are "templated" so to speak, using thereby a c++ expression. They are defined like this :
public delegate TResult Func<in T, out TResult>(T arg);
And you can used them like this :
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 taking as argument and returning a double.
Now imagine that instead of thefunction2 I would like to use a "function" that is nowhere defined for now, by a statement, and that I will never use later. Then c# allows us to use the expression of this function. By expression I mean the "mathematical" (or functional, to stick to programs) expression of it, for instance : to a double x I will associate the double x*x. In maths you write this using the "\mapsto" latex symbol. In c# the functional notation has been borrowed : =>. For instance :
Func<double, double> thefunctor = ( (double x) => x * x ); // outer brackets are not
// mandatory
(double x) => x * x is an expression. It is not a type, whereas delegates (generic or not) are.
Morality ? At end, what is a delegate (resp. generic delegate), if not a function pointer type (resp. wrapped+smart+generic function pointer type), huh ? Something else ! See this and that.
Well, the really oversimplified version is that a lambda is just shorthand for an anonymous function. A delegate can do a lot more than just anonymous functions: things like events, asynchronous calls, and multiple method chains.

Categories

Resources