xaria
xaria

Reputation: 842

Using lambda expressions for method call

See I have this sample code

_service.GetCustomers((customers, error) =>
          {
             if (error != null)
             {                     
                MessageBox.Show(error.Message);
                return;
             }

             Customers = new ObservableCollection<CustomerViewModel>(customers);
             IsBusy = false;
          });

If I were to make a similar function call to another function which accepts more parameters how would that be. The function definition is like this

GetCustomers(DateTime sTime, int ID,  Action<IEnumerable<CustomerViewModel>, Exception> callback)

So how would the above function be invoked using the lambda expression?

Upvotes: 0

Views: 4116

Answers (3)

Michael Brown
Michael Brown

Reputation: 9153

The lambda expression is shorthand for an anonymous delegate which was introduced in C# 2.0 Action<T> and its siblings are generic delegates. Whenever you see an parameter of type Action<T> you can replace it with a lambda taking equivalent parameters. In this case it would be

service.GetCustomers(sometime, someId, (viewmodels, exception)=>{/*handle callback here*/});

Upvotes: 2

Shekhar_Pro
Shekhar_Pro

Reputation: 18430

Simply pass your anonymous delegate as before along with other parameters.

_service.GetCustomers(datetime, id, (customers, error) => {

                    if (error != null)
                    {                     
                        MessageBox.Show(error.Message);
                        return;
                    }

                    Customers = new ObservableCollection<CustomerViewModel>(customers);
                    IsBusy = false;

               });

Upvotes: 2

Jimmy
Jimmy

Reputation: 91502

_service.GetCustomers(datetime, id, (customers, error) => .....
... same as before

Upvotes: 2

Related Questions