0

I would like to dispose of an object a certain way, known to a factory at build time. So in the constructor of my object, I pass a parameterless function to be performed when being disposed of.

How can one construct an Action from a lambda in csharp ?

in pseudo code that is :

var dispose = new Action( ()  => { some side effect });
5
  • 1
    Why is it a pseudocode? Commented Oct 3, 2013 at 9:59
  • I did not realize csharp had unit sometimes. the irregularity in type and syntax is so confusing Commented Oct 3, 2013 at 10:01
  • I guess that makes your question an answer Commented Oct 3, 2013 at 10:02
  • have you look at out over internet.. stackoverflow.com/questions/6495058/… Commented Oct 3, 2013 at 10:04
  • @TejasVaishnav daslinkenlight is right : it actually works. I was just confused about how Action, Func, (), {}, were all acting together, but what I ended up writing as pseudo code actually flow through the rules of csharp as being valid Commented Oct 3, 2013 at 10:25

1 Answer 1

3

If you don't want to use the Action constructor, you can always specify you variable type explicitly, which is often required when it comes to actions, funcs and expressions.

Like this:

Action dispose = () => { /* do something */ };
Action<int> dispose = someInt => { /* do something with the 'someInt' parameter */ };
Action<int, string> dispose = (someInt, someString) => { /* do something with the two parameters */ };

The reason why you can't use var here is because this could just as well be an expression

/* equally valid */
Expression<Action<<int, string>> dispose = (someInt, someString) => /* do something with the two parameters */ ;

The only requirement for the Expression variation is that the body of your action can only be one line of code. (you can't use curly braces)

This is the reason why "var" does not work in this context, the compiler can't determine if you're specifying an action or an expression of an action:

/* will not compile */
var dispose = (someInt, someString) => /* do something with the two parameters */ ;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.