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?
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 () .
The anonymous function is not supported by standard C programming language, but supported by some C dialects, such as GCC and Clang.
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();
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.
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"))();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With