Home » c# » C# Self Executing Anonymous Function

C# Self Executing Anonymous Function

arct-059Not because it is all that new, but because it took me a while to find it, here’s how to create a self executing anonymous function using CSharp, just like you can do in JavaScript.

((Func<int>)(delegate()
{
return 0;
}))();

 

 

Func<int> says the the delegate will return an integer.  If you need to pass a parameter you can use the alternate form of Func<parameterType,returnType>

delegate() {return 0;} is just basic delegate syntax that I’ve discussed in the past.

The parentheses around everything just force the order of operation so the compiler can deal with it all.

And here is the code that I needed this for

list = schools.Select(school => new SchoolItem
{
... code omited ...
    Percentage = ((Func<int>)(delegate()
    {
        var r = 0;
        var found = collectionInOuterScope
             .Find(x => x.ID == school.Id);
        if (found != null)
        {
            r = found.Percentage;
        }
        return r;
    }))()
}).ToList();

Yes, I could have just created a function and called it, but it hardly seems worth it when I’m going to call it in one place.

 

Other post in c#

About Dave Bush

Dave Bush is a Full Stack ASP.NET developer focusing on ASP.NET, C#, Node.js, JavaScript, HTML, CSS, BootStrap, and Angular.JS. Does your team need additional help in any of the above? Contact Dave today.

Leave a Reply

3 Comments on "C# Self Executing Anonymous Function"

Notify of
avatar
Sort by:   newest | oldest | most voted
trackback

[…] Self Executing Anonymous Function (Dave M. Bush) […]

@velvetflair
Guest

Self Executing Anonymous Function http://t.co/afDXJEKZYy

@taswarbhatti
Guest

Self Executing Anonymous Function | http://t.co/DdKrzwHKUc

wpDiscuz