views:

95

answers:

1

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?

+9  A: 

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"))();
Timwi
its very cool... :)
Ramesh Vel
Thank you very much! I should guess myself.
Alexander Prokofyev
Will accept your answer in 8 minutes. :)
Alexander Prokofyev
[No rush :)](http://meta.stackoverflow.com/questions/700/)
Timwi