Reputation: 3988
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).
Upvotes: 6
Views: 7482
Reputation: 5750
new Action<int>(x => Console.WriteLine(x))(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); })(3);
Upvotes: 20
Reputation: 24385
To create an anonymous method use delegate:
delegate(...your arguments...) { ...your code... };
Edit: After the question was revised pablitos answer is more accurate.
Upvotes: 1
Reputation: 1821
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);
Upvotes: 8