Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call anonymous function in C#?

Tags:

I am interested if it's possible using C# to write a code analogous to this Javascript one:

var v = (function() {     return "some value"; })() 

The most I could achieve is:

Func<string> vf = () => {     return "some value"; };  var v = vf(); 

But I wanted something like this:

// Gives error CS0149: Method name expected var v = (() => {     return "some value"; })(); 

Are there some way to call the function leaving it anonymous?

like image 772
Alexander Prokofyev Avatar asked Oct 13 '10 12:10

Alexander Prokofyev


People also ask

How do you call an anonymous function?

The () makes the anonymous function an expression that returns a function object. An anonymous function is not accessible after its initial creation. Therefore, you often need to assign it to a variable. In this example, the anonymous function has no name between the function keyword and parentheses () .

Does C have anonymous function?

The anonymous function is not supported by standard C programming language, but supported by some C dialects, such as GCC and Clang.

What is anonymous function with example?

An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation. Normal function definition: function hello() { alert('Hello world'); } hello();

How do you declare anonymous function in C++?

In C++11 and later, a lambda expression—often called a lambda—is a convenient way of defining an anonymous function object (a closure) right at the location where it's invoked or passed as an argument to a function.


1 Answers

Yes, but C# is statically-typed, so you need to specify a delegate type.

For example, using the constructor syntax:

var v = new Func<string>(() => {     return "some value"; })();  // shorter version var v = new Func<string>(() => "some value")(); 

... or the cast syntax, which can get messy with too many parentheses :)

var v = ((Func<string>) (() => {     return "some value"; }))();  // shorter version var v = ((Func<string>)(() => "some value"))(); 
like image 73
Timwi Avatar answered Sep 17 '22 18:09

Timwi