views:

471

answers:

4

Can I dynamically create a function and invoke it (passing values into it) in one line of code?

Clarification: I was looking for some way that could allow me to create an anonymous function and then calling it directly. Sort of:

delegate(string aa){ MessageBox.show(aa); }("Hello World!");

or something like that (I know the above code does not compile, but I wanted something close).

+1  A: 

Check out anonymous methods.

Gerrie Schenck
it does not requires another line, see my answer
pablito
A: 

To create an anonymous method use delegate:

delegate(...your arguments...) { ...your code... };

Edit: After the question was revised pablitos answer is more accurate.

Sani Huttunen
To downvote an answer that is incorrect AFTER the question was revised/changed seems to me is not how voting should work.
Sani Huttunen
@CKret: welcome to the internet, where people downvote you without a reason, all the time! ;) I've upvoted your answer though.
DrJokepu
Thank you and thank you. ;)
Sani Huttunen
Nitpicking, actually the question did not change.. I goes back to clarify because I feel that I need to. But anyway, thanks.
Hao Wooi Lim
+16  A: 

Of course

new Action<int>(x => Console.WriteLine(x)).Invoke(3);

it's not so readable but answering your question, you definitely can.

EDIT: just noticed you tagged it as c# 2.0, the answer above is for 3.5, for 2.0 it would be

new Action<int>(delegate(int x) { Console.WriteLine(x); }).Invoke(3);
pablito
Thanks.. there seems to be a minor error though... Shouldn't it be new Action<string>(delegate(string x) { Console.WriteLine(x) }).Invoke("Hello World"); // I used delegate instead.
Hao Wooi Lim
in 3.5 works (I checked it), in 2.0 you need to to write as you suggested
pablito
ok just saw it's tagged c#2.0 I fixed my answer
pablito
+6  A: 

The .Invoke is actually not needed; you can just write:

new Action<int>(x => Console.WriteLine(x))(3);

or for C# 2.0:

new Action<int>(delegate(int x) { Console.WriteLine(x); })(3);
gavrie
nice one, didn't know that.
pablito