简体   繁体   中英

How to call anonymous function in C#?

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?

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"))();

Here's how you could then utilize such a construct to enclose context - closure-

Control.Click += new Func<string, EventHandler>((x) =>
new System.EventHandler(delegate(object sender, EventArgs e)
{

}))(valueForX);

Let

With this helper function:

T Let<T>(Func<T> f) => f();

your example is then:

var v = Let(() => { return "abc"; });

Why the name Let ?

It can be used similarly to let in other languages like Haskell, Scheme, and other Lisps.

This in Scheme:

(define c 
  (let ((a 10)
        (b 20))
    (+ a b)))

and this in Haskell:

c = 
  let 
    a = 10
    b = 20
  in a + b

can be written using Let in C#:

var c = Let(() => 
{
    var a = 10;
    var b = 20;

    return a + b;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM