Hao Wooi Lim
Hao Wooi Lim

Reputation: 3988

Create a function and call it in one line of C# code

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

Answers (4)

Pablo Retyk
Pablo Retyk

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

Sani Huttunen
Sani Huttunen

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

gavrie
gavrie

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

Gerrie Schenck
Gerrie Schenck

Reputation: 22368

Check out anonymous methods.

Upvotes: 2

Related Questions