Home > Net >  Delegate vs lambda in class member assigning
Delegate vs lambda in class member assigning

Time:06-28

I was implementing a DatePickerFragment in Xamarin.Android and was following the offical docs. And noticed something strange.

The handler was declared like this

Action<DateTime> _dateSelectedHandler = delegate { };

Having using lambda expressions mostly via Linq and threading. I wanted to change this to a lambda bc from my experience they are the same thing. Even when I hover my mouse over the delegate the tool tip says "Lambda expression".

So I tried this:

Action<DateTime> _dateSelectedHandler = () => { };

The error I get here is that Delegate action doesnt take 0 argument. But what arguments were being captured in my first example? Figured it was because of the Action class so I did this:

Action<DateTime> _dateSelectedHandler = (aux) => { };

In this case aux is of type DateTime which is ok. However, I was still a big confused. I consulted a book my collegues recommended. C# 8.0 in a Nutshell The Definitive Reference by J. Albahari and E. Johannsen. There I found that a delegate is an object that calls a method while a lambda expression is a method written in place of a delegate instance. By this definition why would we as developers ever use a delegate? A delegate is just a lambda with extra steps.

CodePudding user response:

(aux) => { }; is a lambda statement. Note that aux does not have a type yet. Action<DateTime> on the other hand is a delegate, and has a specific type. The parameter type in the lambda statement is inferred from the type of the delegate it is assigned to. So lambda statements can be viewed as syntactic sugar on top of delegates.

Personally I tend to use the built in Func<> / Action<> delegates instead of creating custom delegates. And I tend to create delegates by assigning a lambda function instead of creating them explicitly, and let the compiler do its thing to deduce the types.

But that does not mean that delegates are not used to make the whole system work, it is just rare that you need to use the delegate keyword.

  • Related