Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 801
Hao Wooi Lim Avatar asked Jan 29 '09 07:01

Hao Wooi Lim


People also ask

How do you write and call a function in C?

Syntax to Call a Function We can call a C function just by passing the required parameters along with function name. If function returns a value, then we can store returned value in a variable of same data type. int sum = getSum(5, 7); Above statement will call a function named getSum and pass 5 and 7 as a parameter.

How do you call a function in C?

Function Calling: It is only called by its name in the main() function of a program. We can pass the parameters to a function calling in the main() function. Syntax: Add(a, b) // a and b are the parameters.

Can you call a function in a function in C?

Nested function is not supported by C because we cannot define a function within another function in C. We can declare a function inside a function, but it's not a nested function.

Can functions in C call themselves?

Recursive Functions in C ProgrammingFunctions in C programming are recursive if they can call themselves until the exit condition is satisfied.


2 Answers

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);
like image 22
gavrie Avatar answered Oct 02 '22 17:10

gavrie


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);
like image 52
Pablo Retyk Avatar answered Oct 02 '22 18:10

Pablo Retyk