Home » none » Self Executing Anonymous Function

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.

   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;

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 […]
  • 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 […]
  • 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 […]
  • 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 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.

One Pingback/Trackback