What does the '=>' in this statement signify?
del = new SomeDelegate(() => SomeAction());
Is the above declaration the same as this one?
del = new SomeDelegate(this.SomeAction);
Thanks.
What does the '=>' in this statement signify?
del = new SomeDelegate(() => SomeAction());
Is the above declaration the same as this one?
del = new SomeDelegate(this.SomeAction);
Thanks.
The "=>" can be read "goes to" (source: Eric Lippert), and simply separates the argument(s) from the operation in a lambda expression. In this case, a lambda is overkill. Better examples would be:
(find all items where the item's type is Foo)
etc. In C# 2.0, this can also be written:
And is a quick way of expression a function "inline", while also offering "closure" support - i.e. it could also be:
To do this otherwise would require a type-definiton to pass in the item-type:
In fact, this is pretty-much exactly what the compiler does for us (both for "delegate" and lambda usage). The biggest difference is that a lambda can also express an
Expression
, for example for LINQ.They do the same thing but the "() => ..." syntax is what is called a lambda expression and as such is the same as an anonymous function. You could probably leave out the delegate part altogether and just let the compiler infer the delegate type for you.
Depending on what type "del" is seclared as.
Edit
Using lambdas or anonymous methods or just a regular method for starters enables you to map methods that didn't have the delegate's signature to the delegate.
For example, say you have a delegate with the signature bool myDelegate(int, int) but you wanted to have a method with the signature bool myMethod(string, string) handle the delegate. You could then use the lambda expression to let you do this inline with a short syntax like so.
So as you can see lambdas and anonymous methods are basically just a shorter/inline way of making a method to handle the delegate. In you case you might not need to make an extra method. It just depends on if the delegate signature is the same as your method signature, and to me, it seems like it is.
Basically it's specifying an anonymous function, that takes no parameters that calls SomeAction. So yes, they are functionally equivalent. Though not equal. Using the lambda is more equivalent to:
where CallSomeAction is defined as:
Hope that helps!
=>
is the Lambda Operator, lambda expressions are like an evolution of the C# 2.0 anonymous methods.You can use anonymous methods and lambda expressions in a very similar way to create delegate instances:
Using lambda expressions: