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.

Related Post

  • Easily Find Classes, Methods, and VariablesEasily Find Classes, Methods, and Variables There is a bit of a "trick" that I use routinely in Visual Studio to help me find the definition of Classes, Methods, and Variables in my solution regardless. This "trick" works in […]
  • Determine The Role of a User in ASP.NETDetermine The Role of a User in ASP.NET There are several controls that allow you to display content based on the role a user is in, including: - LoginView - LoginStatus And the web.config file allows us to control which […]
  • CSharp VAR MisconceptionsCSharp VAR Misconceptions I find it amazing that .NET 3.5 has been out for over a year and people still don’t understand the “var” keyword. Just last week I got a comment on one of my videos asking why I used […]
  • Type Safe Session VariablesType Safe Session Variables This may be obvious to everyone else on the Internet.  Heck, it's been obvious to me for several years.  But I can’t find anyone else writing about this and it makes so much […]
  • ASP.NET Assigning a Role to a UserASP.NET Assigning a Role to a User Another function that is not supplied by one of the existing controls in ASP.NET is the ability to assign a user to a role.  For this, we will need to resort to using the APIs. […]

About Dave Bush

Dave Bush is a .NET programmer and Certified ScrumMaster who is passionate about managing risk as it relates to developing software. When he is not writing or speaking about topics related to Application Lifecycle Risk Management (ALRM), he is an example to his peers as he develops web sites in the ASP.NET environment using industry best practices.

One Pingback/Trackback

Awards & Certs