Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a Lambda Expression in a Variable

Tags:

c#

I think my brain has become fried as i'm struggling to do something simple. In my application i have the following code to configure Nhibernate (my issue is not specific to Nhibernate).

return Fluently.Configure()     .ExposeConfiguration(c => {         c.EventListeners.PostInsertEventListeners = new IPostInsertEventListener[] { new LoggingEventListener() };         c.EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[] { new LoggingEventListener() };    }); 

However I need to store the configuration (the stuff inside ExposeConfiguration) inside a private variable. I can do the following:

return Fluently.Configure()     .ExposeConfiguration(c => _configuration = c); 

Where _configuration is a private variable. But this doesn't add my extra configuration options (the EventListeners stuff). I've played around with various things but i guess my lambda knowledge isn't as good as i thought.

I'd appreciate your help. Thanks

like image 644
nfplee Avatar asked Dec 07 '10 16:12

nfplee


People also ask

Can a lambda be put in a variable?

Lambda expressions can use variables defined in an outer scope. We refer to these lambdas as capturing lambdas. They can capture static variables, instance variables, and local variables, but only local variables must be final or effectively final.

How do you declare a variable in lambda expression in Java?

A lambda expression can't define any new scope as an anonymous inner class does, so we can't declare a local variable with the same which is already declared in the enclosing scope of a lambda expression. Inside lambda expression, we can't assign any value to some local variable declared outside the lambda expression.

How do you declare a lambda expression?

To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator and an expression or a statement block on the other side. When you use method-based syntax to call the Enumerable. Select method in the System.

How do you declare lambda in C++?

Creating a Lambda Expression in C++auto greet = []() { // lambda function body }; Here, [] is called the lambda introducer which denotes the start of the lambda expression. () is called the parameter list which is similar to the () operator of a normal function.


1 Answers

A lambda expression is just a delegate that often maps to one of the Func<T1, T2, ..., TResult> variants.

Func<T1, TResult> myVar = c => _configuration = c; 

Replacing TResult and T1 with the relevant types.

That might work for you.

like image 170
Colin Mackay Avatar answered Sep 24 '22 17:09

Colin Mackay