How to make an anonymous method accept variable number of arguments? - c#

I'd like to be able to make inline calls to anonymous methods with variable number of arguments (sometimes with no arguments, sometimes with 11).
Dictionary<string, Action> ActionDic = new Dictionary<string, Action>();
int i = 0;
ActionDic["something"] = () => { i += 1; }; // this line is ok
ActionDic["somethingArgs"] = (int n) => { n += 1; }; // but this is not
// Delegate 'System.Action' does not take 1 arguments
So I can't make a delegate accept arguments like that. Is my syntax wrong, or is it just not possible? Or do I have to change the type of anonymous method I should use for my dictionary?

You could use Action<int> if you want to define a delegate with 1 integer argument. For example:
Action<int> somethingArgs = (int n) => { n += 1; };
You haven't shown what the ActionDic variable is but if it is an IDictionary<string, Action> you cannot make this work because Action do not accept an argument.
What you could do on the other hand is to use a dictionary of delegates:
IDictionary<string, Delegate> ActionDic = ...
ActionDic["something"] = (Action)(() => { i += 1; });
ActionDic["somethingArgs"] = (Action<int>)((int n) => { n += 1; });

You can't. Action and Action<T> are different, incompatible delegate types.
There are several ways to compensate for this.
One would be to make ActionDic a Dictionary<string, Action<int>> but that may not satisfy all possible delegates you would want to use.
Another would be to make ActionDic something like a Dictionary<string, Delegate> but this would cumbersome to use because you need to know exactly how many many parameters (and their types) to pass each function. This information would need to be stored in another data structure somewhere.
Still a third way would be to make ActionDic a Dictionary<string, Action<object[]>> and require the delegate to unpack whatever arguments it needs from the input. The caller would be responsible for knowing exactly what arguments to use. This would allow somewhat less awkward syntax of the second option, but require more code in each delegate.

You are talking about two different delegates, i.e. Action and Action<T>. You cannot assign Action<T> to Action:
Action a1 = () => { i += 1; };
Action<int> a2 = (n) => { n += 1; };
I suppose you're having Dictionary<string,Action>, so this dictionary cannot accept a value of Action<T>.
As a side note, I'd say that the second delegate is absolutely useless, as it increments an int argument, passed by value, that is in fact doing nothing.
Also consider reading How To pass Optional Arguments. Though it has nothing to do with anonymous methods, but it may give you some clue on how to pass variable number of arguments

Action is a short way to create a delegate that returns void and take no argument.
If you want actions with argument, you need to use generic form :
Action<int> is a delegate that takes one int parameter
Action<string, double> takes 2 parameters : first is string second is double.

Related

C#.Net Delegates

Say I have a method that calls another method that accepts a string and returns a string, over and over until a condition is met:
public string RetryUntil(
Func<string, string> method,
string input,
Func<string, bool> condition,
TimeSpan timeSpan)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
string response = string.Empty;
bool conditionResult = false;
while (stopwatch.Elapsed < timeSpan && conditionResult != true)
{
result = method(input);
conditionResult = condition(result);
Thread.Sleep(TimeSpan.FromSeconds(0.5));
}
return response;
}
It really feels like I should be able to specify the 'method' and 'input' parameters as one parameter. So, I want to refactor it so I am able to call it like this, for example:
RetryUntil(
ConvertString("hello World"),
(str) => { return str == "whatever"; },
TimeSpan.FromSeconds(10));
But obviously, this would pass the result of calling the ConvertString method, (rather than just a delegate to that method) into the Retry method. Is there a way to pass both delegates and specific parameters for those delegates as one? Am I thinking about the entire problem backwards? It just feels a bit inelegant the way I'm doing it now.
What you're looking for is often called "currying" and is not directly supported in C#, or at least not as well as it is in F#. This is a feature where you can specify some arguments of a function, and get a delegate which takes the remaining arguments (if any) and returns the appropriate value.
The easiest way to reference this is like so:
public string RetryUntil(
Func<string> method,
Func<string, bool> condition,
TimeSpan timeSpan)
And then call via
RetryUntil(
() => ConvertString("Hello World!"),
// ...
the => creates a lambda, which will return the result of the given function. Since you're now declaring a method call, you can pass in whatever parameters you wish, or make the lambda itself take some parameters, thus currying arguments.

How can I use System.Func?

I have trouble using System.Func.
public Func<int> OnCreated=new Func<int>(int ASD){ Debug.Log (ASD); };
Is this the proper way to use it? I want to make a dynamic function that can be called. Also can the System.Func be serialized via XML?
Maybe you're looking for Action<> instead?
Action<int> myAction = myIntParam => Debug.Log(myIntParam);
myAction(myInteger);
If you want to take an input parameter, and return something, you should use Func<>
Func<int, int> myFunc = myIntParam => {
Debug.Log(myIntParam);
return 5;
};
int five = myFunc(myInteger);
Also, if you want to serialize/deserialize, you need to take it one step further. Namely, by def Func does not really have any meaningful information for it to be serialized, you should wrap it in Expression. You can get started by googling for "C# serialize expression", eg: https://expressiontree.codeplex.com
Just like any other thing in .NET Func is an Object. Func is an object of type Delegate.You can serialize/deserialize any serializable object. Func returns a value and can take up to 16 parameters.
The way you would use it is like this :
Func<int> w = new Func<int>(() => { return 1; });
You should first be familiar with the use of delegates. Check this : when & why to use delegates?
P.S Serializing delegates is a risky thing to do since they are pointers to functions that are inside your program.|
You can check how you can do the serialization over here : Could we save delegates in a file (C#)

Questions on delegate functions in C#?

I'm learning about C# and one of the areas that interested me were delegate functions. The following code uses them to apply a function to each number in a range [start, limit[ before it is summed. This is a fairly simple example for clarity.
// function passing a delegate function
public override void solveProblem() {
int squareOfSum = (int) Math.Pow(Library.Math.sumRange(1, 101), 2);
int sumOfSquares = Library.Math.sumRange(1, 101, new Func<double, double, double>(Math.Pow), 2);
this.solution = (squareOfSum - sumOfSquares).ToString();
}
// function that accepts / uses delegate function
static public int sumRange(int start, int limit, Delegate operation, params object[] args) {
int sum = 0;
for (int current = start; current < limit; current++) {
// add the current number in the range as an arguement
object[] newArgs = new object[args.Length + 1];
newArgs[0] = current;
args.CopyTo(newArgs, 1);
// sum the result of the operation (delegate function)
sum += Convert.ToInt32(operation.DynamicInvoke(newArgs));
}
return sum;
}
The specific questions I have are:
Is it possible to use dynamic delegate functions (that accept a variable length list of parameters with unkown types) but force the delegate function to return a specific type? With non-dynamic delegate functions you set a return type, but also have to set the number of parameters and their types.
How much slower is using DynamicInvoke than using a non-dynamic delegate function?
What is the best way to handle parameters than what I currently do (which is accept a list of other parameters and prepend any parameters the function that uses the delegate needs to add in)?
Do I need to declare 'new Func(Math.Pow)' to pass in the power function, or is there a way to just pass Math.Pow (and have the return type and parameters be passed implicitly)?
I've looked at the C# docs and this StackOverflow question to learn how to use delegate functions, I just want to learn more about them.
Thanks!
jtfairbank
Is it possible to use dynamic delegate functions (that accept a
variable length list of parameters with unkown types) but force the
delegate function to return a specific type? With non-dynamic delegate
functions you set a return type, but also have to set the number of
parameters and their types.
You don't "force" the function to return something. The function returns something or it doesn't return something. The function "forces" you to accept something :-) (or to ignore it)
You can call a dynamic delegate through the DynamicInvoke and then cast the return value to what you know your delegate returns (or you keep it as an object). I say "what you know your delegate returns" but the reality is a little more complex: for Value Types you have to cast the return value to precisely the type used as return value or you'll get InvalidCastException. For reference types you can use an interface or a base class of the object returned (with some exceptions for Nullable types)
How much slower is using DynamicInvoke than using a non-dynamic delegate function?
I've tested a void Do() method (the most simple method possible, with no boxing for parameters) and the time difference was demential. Let's say 400x :-) On http://ideone.com/f34cj it's between 70x and 150x.
Do I need to declare 'new Func(Math.Pow)' to pass in the power function, or is there a way to just pass Math.Pow (and have the return type and parameters be passed implicitly)?
Creating a new Func/Action delegate is the right path.
In general the right solution is not what you are doing. The right solution is do as LINQ does. For example:
int pow = 2;
Func<int, int> myFunc = p => (int)Math.Pow(p, pow);
var listOfNumbers = Enumerable.Range(1, 100);
var result = listOfNumbers.Sum(p => myFunc(p));
Now, you have a delegate (myFunc) that takes a number and returns the square of that number (and note that through "closures" it closes around pow) (if you don't know what a closure is, try putting that word in google with the words lambda function). A list of numbers as an IEnumerable<int> and you do the sum of these numbers "converted" by myFunc.
Read on LINQ - usage of IEnumerable produces much more compact code.
I.e. combination of Enumrable.Range ( http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx ) and Enumerable.Aggregate ( http://msdn.microsoft.com/en-us/library/bb548651.aspx ) is exactly what you trying to achieve:
var sum = Enumerable.Range(start,limit).Aggregate((s, cur)=> s+cur);
var sumSq = Enumerable.Range(start,limit).Aggregate((s, cur)=> s+ cur * cur);

How to create a fully parameterized method delegate in C#?

In c# we can create delegates via a variety of means (e.g. Action<>, Func<>, delegate, lambdas, etc). But when you invoke those methods, you have to provide the parameter values for the delegate you are invoking:
delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5);
Is there a way in c# to encapsulate a method delegate WITH parameter values? Essentially delay invocation of a fully parametrized method? So you don't have to supply parameter values at invocation time?
For example something like this invalid code:
delegate int del(int i);
del myDelegate(5) = x => x * x;
int j = myDelegate;
I'm aware the use case isn't immediately obvious. In the case I'm currently looking at, I have a non-deterministic method that I would like the caller to be able to invoke without having to contain or be aware of the parameters the method needs. One way to achieve this would be via creating a class that encapsulates both the parameter values and the method delegate and have that referenced and invoked by the caller. But I'm just curious if there is an alternate, more succinct way.
This is called currying.
For example:
Action curried = () => myFunc(5);
Or,
Func<int, int, int> multiplier = (x, y) => x * y;
Func<int, int> doubler = x => multiplier(x, 2);
int eight = doubler(4);
Func<int, int> myDelegate = x => x * x;
Func<int> myDelegate5 = () => myDelegate(5);
int j = myDelegate5();
You could always wrap one delegate in another. As SLaks mentioned, this is called currying:
Func<int, int> square = i => i * i;
Func<int> squareFive = () => square(5);
int j = squareFive();
This can be done reasonably nicely without lambdas, with the aid of some generic classes and helper functions. I used such an approach in some vb.net/vs2005 code. If the goal is to yield a MethodInvoker which calls a function with three arguments of types T, U, and V, then create a class ParamInvoker<T,U,V> which holds fields param1, param2, and param3 (as types T, U, and V), and Action (of type Action<T,U,V>) and has a method DoIt(void) which calls Action(param1, param2, param3). The generic classes and helper functions get repetitive, but the syntax is pretty nice. For example (vb syntax, from memory, and C# syntax, guessing):
TheMethodInvoker = MakeParamInvoker(AddressOf MyFunction, 5, "Hello")
or
TheMethodInvoker = MakeParamInvoker(MyFunction, 5, "Hello")
assuming MyFunction takes an Integer and a String.

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