tags:

views:

105

answers:

3

Is there any way to combine the following two lines into a single statement?

Func<XmlNode> myFunc = () => { return myNode; };
XmlNode myOtherNode = myFunc();

I've been trying things like the below but can't get it to work and can't determine from the documentation whether it should work or not?

XmlNode myOtherNode = ((Func<XmlNode>) () => { return myNode; })();
+5  A: 

I'm not sure why you are looking to do this but ..

XmlNode myOtherNode = new Func<XmlNode>( () => { return myNode; } )();

should do the trick.

headsling
+2  A: 

The 'trick' is that you need to create an instance of a delegate in order for it to work, which in your example is implicity done when you do the assignment (myFunc = ...). Also, you can express your function as () => myNode to make it shorter.

XmlNode myOtherOne = new Func<XmlNode>( () => myNode )();
Trap
+2  A: 

The syntax posted by "headsling" works.

Oddly, even though you can't use the original syntax with lambda (=>), you can with delegate:

XmlNode myOtherNode = ((Func<XmlNode>) delegate { return myNode; })();

Of course, the real question is... why? What is wrong with...

XmlNode myOtherNode = myNode;
Marc Gravell
"Of course, the real question is... why?": I want to do more within the anonymous method than just that one statement.
sipwiz
So refactor to a method perhaps... or whatever you're happy with.
Marc Gravell