I am still reading documentation about C# and I fell on anonymous functions.
It is true that they prioritize lambda expressions against it but,
they also said right after :
There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions.
This (quotation) is what I want to understand with some few examples if needed. Thank you.
If you ignore the parameters in a delegate then with anonymous function syntax using delegate you can leave them out:
Action<int> a = delegate { Console.WriteLine("I am ignoring the int parameter."); }; //takes 1 argument, but not specified on the RHS
a(2); // Prints "I am ignoring the int parameter."
There is no way of doing this with lambda expressions:
Action<int> a = => { Console.WriteLine("I am ignoring the int parameter."); }; // syntax error
Action<int> a = () => { Console.WriteLine("I am ignoring the int parameter."); }; // CS1593 Delegate 'Action<int>' does not take 0 arguments
It's not terribly useful, but it can be a bit handy when you know you want something done on an event and don't even care what it's signature is.
button.OnClick += delegate { Console.WriteLine("Button clicked and that's all I care about"); };
Historically the big advantage anonymous functions had in C# 2.0 was that they existed. Lambda syntax didn't get introduced until C# 3.0.
Related
Suppose I had this in C#:
class OverloadTest
{
void Main()
{
CallWithDelegate(SomeOverloadedMethod);
}
delegate void SomeDelegateWithoutParameters();
delegate void SomeDelegateWithParameter(int n);
void CallWithDelegate(SomeDelegateWithoutParameters del) { }
void CallWithDelegate(SomeDelegateWithParameter del) { }
void SomeOverloadedMethod() { }
void SomeOverloadedMethod(int n) { }
}
Of course, this does not compile, because the line CallWithDelegate(SomeOverloadedMethod); is ambiguous.
Now, suppose there was only one CallWithDelegate(SomeDelegateWithoutParameter del) function (no overloads). In this case, there would be no ambiguity, because, from what seems to be happening, the compiler can look at the parameter type and discard SomeOverloadedMethod(int n) from the candidate list (since it can only take a SomeDelegateWithoutParameters), and so it compiles.
I don't intend to write code like this; this is just out of curiosity, from a compiler writer point-of-view. I couldn't find an answer about this, since it is quite confusing to put into words.
I'd like to know if there is any way in C# to disambiguate that call in Main() in the example given, so that it would compile. How can you specify it so that it resolves into CallWithDelegate(SomeDelegateWithoutParameters del) being passed SomeOverloadedMethod(), or CallWithDelegate(SomeDelegateWithParameter del) being passed SomeOverloadedMethod(int n)?
There are several ways to disambiguate overload resolution of method groups.
Method 1: cast the method group
CallWithDelegate((SomeDelegateWithoutParameters)SomeOverloadedMethod);
CallWithDelegate((SomeDelegateWithParameter)SomeOverloadedMethod);
This disambiguates the overload. That's pretty uncommon syntax in the wild, but it works (C# 5 spec §6.6 Method group conversions):
As with all other implicit and explicit conversions, the cast operator can be used to explicitly perform a method group conversion.
[...]
Method groups may influence overload resolution, and participate in type inference.
Method 2: instantiate the delegate explicitly
CallWithDelegate(new SomeDelegateWithoutParameters(SomeOverloadedMethod));
CallWithDelegate(new SomeDelegateWithParameter(SomeOverloadedMethod));
This is the same as the previous method without the syntactic sugar. See the spec at §7.6.10.5 Delegate creation expressions for more details.
The binding-time processing of a delegate-creation-expression of the form new D(E), where D is a delegate-type and E is an expression, consists of the following steps:
If E is a method group, the delegate creation expression is processed in the same way as a method group conversion (§6.6) from E to D.
[...]
There's even an example closely related to your question:
As described above, when a delegate is created from a method group, the formal parameter list and return type of the delegate determine which of the overloaded methods to select. In the example
delegate double DoubleFunc(double x);
class A
{
DoubleFunc f = new DoubleFunc(Square);
static float Square(float x) {
return x * x;
}
static double Square(double x) {
return x * x;
}
}
the A.f field is initialized with a delegate that refers to the second Square method because that method exactly matches the formal parameter list and return type of DoubleFunc. Had the second Square method not been present, a compile-time error would have occurred.
Method 3: use a lambda
CallWithDelegate(() => SomeOverloadedMethod());
CallWithDelegate(i => SomeOverloadedMethod(i));
CallWithDelegate((int i) => SomeOverloadedMethod(i)); // Explicit types, if needed
This form is not ambiguous but it has an indirection (the lambda is called, and it then calls the target method). This may get optimized by the JIT though, and it most probably won't have a visible performance impact anyway.
Method 4: use anonymous delegates
CallWithDelegate(delegate() { SomeOverloadedMethod(); });
CallWithDelegate(delegate(int i) { SomeOverloadedMethod(i); });
This is equivalent to the lambda calls, but it uses the bulkier (and older) delegate syntax.
If you'd like to know the exact overload resolution rules, they're described in the spec in §7.5.3 Overload resolution.
While i am no compiler expert, I can tell you that since you have supplied 2 overloaded methods that match both methods the compiler has no way of identifying your actual intention. It can't compile because at compile time there is currently no actual identifying information as now mentioned by Lucas you can cast to remove the ambiguity. For the compiler to solve this it would need run-time information of which method you actually wanted to use based on arguments that you may try and pass in.
I discovered some new C# syntax and do not understand what it means. Here is the syntax-related code:
1)
BeginInvoke(new Action(() =>
{
PopulateUI(ds);
}));
2)
private void OnFormLoad()
{
ThreadPool.QueueUserWorkItem(() => GetSqlData());
}
What is the meaning of new Action() and what is the meaning of the => symbol?
The syntax of ThreadPool.QueueUserWorkItem was ThreadPool.QueueUserWorkItem(new WaitCallback(PrintOut), "Hello"); but here it shows ThreadPool.QueueUserWorkItem(() => GetSqlData());, so how does it work? Why is WaitCallback missing? Please explain in detail.
Thanks a lot.
Have a look at
Action Delegate
Encapsulates a method that has a
single parameter and does not return a
value. You can use the Action
delegate to pass a method as a
parameter without explicitly declaring
a custom delegate.
and
and Lambda Expressions (C# Programming Guide)
A lambda expression is an anonymous
function that can contain expressions
and statements, and can be used to
create delegates or expression tree
types.
All lambda expressions use the lambda
operator =>, which is read as "goes
to". The left side of the lambda
operator specifies the input
parameters (if any) and the right side
holds the expression or statement
block. The lambda expression x => x *
x is read "x goes to x times x."
As others have said, it is a lambda, which is basically an anonymous (unnamed) local function.
This might make a bit more sense if you look at some similar code that doesn't use lambdas:
// With a lambda
private void OnFormLoad()
{
ThreadPool.QueueUserWorkItem(() => GetSqlData());
}
// Without a lambda
private void OnFormLoad()
{
ThreadPool.QueueUserWorkItem(ExecuteGetSqlData);
}
private void ExecuteGetSqlData()
{
// If GetSqlData returns something, change this to "return GetSqlData();"
GetSqlData();
}
As for the other code, normally you shouldn't have to do new Action. The problem is that the BeginInvoke method takes a Delegate, which is sort of old school, and breaks how most new code works.
With newer code (that takes something like Action, or a specific type of delegate, like WaitCallback), you either write a lambda, or simply give the name of a function inside your class. The example code I wrote above demonstrates both of these.
Also note that if you see something like: (Action) (() => Blah()), it is pretty much the same as new Action(() => Blah()).
These are known as lambda expressions, which aren't very different from delegates in C#.
The empty () mean there are no arguments, and what's between the (optional) {} are the lambda expression bodies. The => operator simply associates both expressions together to make a lambda expression. As an aside, they're commonly found in LINQ code.
There's nothing special about new Action(), just that it's a delegate that can map a lambda expression to itself.
As for ThreadPool.QueueUserWorkItem(), the WaitCallback argument is a delegate. You can either pass the name of a named delegate as the argument, pass an anonymous delegate object or write a lambda expression for this anonymous delegate (in your case it's () => GetSqlData()).
Lambda expression
Action Delegate
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have been trying to figure this out for quite sometime (reading online blogs and articlaes), but so far unsuccessful.
What are delegates? What are Lambda Expressions? Advantages and disadvantages of both? Possible best practice of when to use one or the other?
Thanks in advance.
Delegates are methods that you can use as variables, like strings etc. For example you can declare a delegate method with one argument:
delegate void OneArgumentDelegate(string argument);
It doesn't do anything, much like an interface. If you have a method in any class with one argument like this:
void SomeMethod(string someArgument) {}
It matches the signature of the delegate, and thus can be assigned to a variable of its type:
OneArgumentDelegate ThisIsAVariable = new OneArgumentDelegate(SomeMethod);
OneArgumentDelegate ThisIsAlsoAVariable = SomeMethod; // Shorthand works too
These can then be passed as arguments to methods and invoked, like so:
void Main()
{
DoStuff(PrintString);
}
void PrintString(string text)
{
Console.WriteLine(text);
}
void DoStuff(OneArgumentDelegate action)
{
action("Hello!");
}
This will output Hello!.
Lambda expressions are a shorthand for the DoStuff(PrintString) so you don't have to create a method for every delegate variable you're going to use. You 'create' a temporary method that's passed on to the method. It works like this:
DoStuff(string text => Console.WriteLine(text)); // single line
DoStuff(string text => // multi line
{
Console.WriteLine(text);
Console.WriteLine(text);
});
Lambda expressions are just a shorthand, you might as well create a seperate method and pass it on. I hope you understand it better now ;-)
Delegate is an object that hold a reference to a function. Several different delegates may point to the same function. A delegate's type defines the footprint of a function it may point to.
Lambda expression is a function that doesn't have name. The only way to execute this function is to have a delegate pointing to the function. Lambda expressions are usually defined in place where you need a delegate to a function with a given footprint. This is useful to make code less verbose and at the same time more descriptive and flexible
I would suggest that you use a named function and a delegate to it whenever you have some code that is going to be called from different places. A common example is an event listener that you want to attach to several event producers.
Another point to consider writing a separate function is the complexity of the code. It isn't going to help anyone if you write a whole program inside a lambda expression.
On the other hand, you often need some trivial processing that you want to be executed in a callback manner. This is the point where you might love the lambda expressions.
What is very nice about lambda expressions that they inherit the scope they were defined in, so that you can easily your variables inside the lambda expression, and thus pass a lot of info inside. You should be careful though, see the Remarks section of
this article.
Labdas are brilliant in conjunction with LINQ.
To conclude, I have to quote yet another must-read msdn section:
When you use method-based syntax to call the Where method in the Enumerable class (as you do in LINQ to Objects and LINQ to XML) the parameter is a delegate type System.Func. A lambda expression is the most convenient way to create that delegate. When you call the same method in, for example, the System.Linq.Queryable class (as you do in LINQ to SQL) then the parameter type is an System.Linq.Expressions.Expression where Func is any Func delegates with up to sixteen input parameters. Again, a lambda expression is just a very concise way to construct that expression tree. The lambdas allow the Where calls to look similar although in fact the type of object created from the lambda is different.
No one has mentioned anonymous delegates. You can create delegates on the fly, without declaring them:
public void Action(Func<int, int> func);
...
Action(delegate(int x) { return x*x; });
Which is just a more verbose version of the lambda syntax:
Action(x => x*x);
Also note that the lambda syntax has more aggressive type inference. Another difference is that the lambda notation can be used to declare expression trees:
public void Action(Expression<Func<int, int>>);
Action(x => x*x);
In which case what you get is not a function but a parse tree that you can examine at runtime. This is how linq queries build their sql, for example.
edit
To more directly answer the question of when to use one or the other:
You rarely need to declare a new delegate type yourself, although it is occasionally helpful. The framework provides several Func<> types, along with Action<T> and Predicate<T> which are usually all that you need.
When creating a function 'on the fly', there is no advantage to using the anonymous delegate syntax instead of the lambda syntax. Since the lambda syntax is more concise and type-inferred, prefer it.
Delegate is just pointer to function. Its just like a "variable", where you can save address to another function that will be called
public class test {
Action<int> CallUserCode;
public test(Action<int> proc){
CallUserCode = proc;
}
void foo(){
int someValue = 0;
//do some stuff that needs to call the user procedure
CallUserCode(someValue);
}
}
Lambda Expressions is too a delegate, which has simplified syntax and can "create" functions "inline".
So the previous example would be called using lambda in following way.
void bar(){
var t = new test(x => { /* do something with the value i get from foo */});
t.foo(); //here function foo gets called, which will call 'do something' AND call my lambda expression
}
There is one important difference is there where we can use lamda than delegate.
private delegate int emptymethoddel();
// Delegate for method with no params and returns int
The equivalent framework delegate type is: Func<int>
But you cannot create new delegate instance/func from parameterized method.
private int TwoArgMethod(int i, int j)
{
return i + j;
}
but, with lambda, you can get delegate for the above method.
Func<int> retmethod = () => TwoArgMethod(10, 20);
but for delegate instantiation, we cannot do as below
emptymethoddel retmethod4 = new emptymethoddel(TwoArgMethod(10,20));
// mismatch method signature
With lambda, we can get pointers to methods that doesn't match "Func" or any other variants.
As the others said, lambdas are a syntax to create delegates inline and anonymously. One thing you can do with lambdas that is not possible with traditional functions are closures. This way you can create functions at runtime with runtime information:
string mystring = SomeObject.GetMyString();
AnotherObject.OnSomeEvent += (eventparams =>
{
string newstring = string.Format(eventparams.Message, mystring);
SomeService.PrintEvent(newstring);
}
This way, mystring is incorporated into the delegate and can be used as a variable.
Several C# questions on StackOverflow ask how to make anonymous delegates/lambdas with out or ref parameters. See, for example:
Calling a method with ref or out parameters from an anonymous method
Write a lambda or anonymous function that accepts an out parameter
To do so, you just need to specify the type of the parameter, as in:
public void delegate D(out T p);
// ...
D a = (out T t) => { ... }; // Lambda syntax.
D b = delegate(out T t) { ... }; // Anonymous delegate syntax.
What I'm curious about is why the type is explicitly required. Is there a particular reason that this is the case? That is, from a compiler/language standpoint, why isn't the following allowed?
D a = (out t) => { ... }; // Lambda syntax -- implicit typing.
D b = delegate(out t) { ... }; // Anonymous delegate syntax -- implicit typing.
or even better, just:
D a = (t) => { ... }; // Lambda syntax -- implicit typing and ref|out-ness.
D b = delegate(t) { ... }; // Anonymous delegate syntax -- implicit typing and ref|out-ness.
Interesting question.
First, consider the difference between anonymous methods and lambdas. From the compiler writer's perspective, the most important difference is that lambdas can require the compiler to infer the type of the parameters from the target to which the lambda is being assigned; C# 2 anonymous methods do not have this feature. This feature seems like a small difference but in fact it has major ramifications on the implementation of the compiler. See my blog series on this topic for some thoughts on why that is:
http://blogs.msdn.com/ericlippert/archive/2007/01/10/lambda-expressions-vs-anonymous-methods-part-one.aspx
So now let's come to your actual question: why can we not infer outness/refness from the target type to the parameters of the lambda. That is, if we have delegate void D(out int x) then surely D d = x=> { x = 10; } could infer that x is "out int".
There's no technical reason I'm aware of why we could not do that. Internally in the compiler the out/ref types are represented as types like any other.
However, features do not get done just because they can be done; they get done because there's a compelling reason to do so. For lambdas, the compelling reason to do type inference in the first place is LINQ; we want to be able to do a simple syntactic transformation on a query comprehension into a method call with lambdas, and let the method type inference engine work out the types of all the lambda parameters. None of the LINQ methods generated have delegates with out or ref parameters.
So, we have no compelling reason to do the feature. Delegates which have out/ref parameters are relatively rare. And assignment of lambdas to those delegates is rarer still. So this is a feature that we don't need, and that benefits almost no one.
C# 3 was the "long pole" on the Visual Studio schedule; we had the most number of days of work scheduled of any team that ships a component in VS. That meant that every day we slipped the schedule, the entire division slipped. That was a powerful disincentive to spending time on unnecessary features that benefitted no one. So the work was never done.
I agree that it would be nice to be more consistent here, but it's unlikely to happen. We have many higher priorities.
From Eric Lippert's comment on why declaration and assignment of a var variable cannot be split:
I agree that in principle this could be done, but it is rather more complicated in practice than your quick sketch would indicate. var not only requires that there be an initializer, it also requires that the initializer not refer to the variable. If you have int M(out int) then you can say "int x = M(out x);" but you cannot say "var x = M(out x);" because to do overload resolution on M, we need to know the type of x, which is what we're attempting to figure out. Would it be legal to say "var s; if (b) M(out s); else s = 0;" ?
I'd guess the answer to your question is similar, considering, for example,
D a = (out var x) => x = M(out x);
With the advent of new features like lambda expressions (inline code), does it mean we dont have to use delegates or anonymous methods anymore? In almost all the samples I have seen, it is for rewriting using the new syntax.
Any place where we still have to use delegates and lambda expressions won't work?
Yes there are places where directly using anonymous delegates and lambda expressions won't work.
If a method takes an untyped Delegate then the compiler doesn't know what to resolve the anonymous delegate/lambda expression to and you will get a compiler error.
public static void Invoke(Delegate d)
{
d.DynamicInvoke();
}
static void Main(string[] args)
{
// fails
Invoke(() => Console.WriteLine("Test"));
// works
Invoke(new Action(() => Console.WriteLine("Test")));
Console.ReadKey();
}
The failing line of code will get the compiler error "Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type".
lambda is shortcut for anonymous delegate, but you will always be using delegates. the delegate specifies the methods signature. you can just do this:
delegate(int i) { Console.WriteLine(i.ToString()) }
can be replaced with
f => Console.WriteLine(f.ToString())
Lambda expression is not (and was not meant to be) a silver bullet that would replace (hide) delegates. It is great with small local things like:
List<string> names = GetNames();
names.ForEach(Console.WriteLine);
it makes code more readable thus simple to understand.
It makes code shorter thus less work for us ;)
On the other hand it is very simple to misuse them. Long or/and complex lambda expressions are tending to be:
Hard to understand for new developers
Less object oriented
Much harder to read
So “does it mean we don’t have to use delegates or anonymous methods anymore?” No – use Lambda expression where you win time/readability otherwise consider using delegates.
One not so big advantage for the older delegate syntax is that you need not specify the parameters if you dont use it in the method body. From msdn
There is one case in which an anonymous method provides functionality
not found in lambda expressions. Anonymous methods enable you to omit
the parameter list. This means that an anonymous method can be
converted to delegates with a variety of signatures. This is not
possible with lambda expressions.
For example you can do:
Action<int> a = delegate { }; //takes 1 argument, but not specified on the RHS
While this fails:
Action<int> a = => { }; //omitted parameter, doesnt compile.
This technique mostly comes handy when writing event-handlers, like:
button.onClicked += delegate { Console.WriteLine("clicked"); };
This is not a strong advantage. It's better to adopt the newer syntax always imho.
Delegate have two meanings in C#.
The keyword delegate can be used to define a function signature type. This is usually used when defininge the signature of higher-order functions, i.e. functions that take other functions as arguments. This use of delegate is still relevant.
The delegate keyword can also be used to define an inline anonymous function. In the case where the function is just a single expression, the lambda syntax is a simpler alternative.
Lambda expressions are just "syntactic sugar", the compiler will generate appropriate delegates for you. You can investigate this by using Lutz Roeder's Reflector.
Lamda's are just syntactic sugar for delegates, they are not just inline, you can do the following:
s.Find(a =>
{
if (a.StartsWith("H"))
return a.Equals("HI");
else
return !a.Equals("FOO");
});
And delegates are still used when defining events, or when you have lots of arguments and want to actually strongly type the method being called.