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.

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.


Other post in c#

Related Post

  • Decimal vs Float (Single) or DoubleDecimal vs Float (Single) or Double When you need to deal with a number that is a fraction, what do you specify for its type?  If you are like most programmers I know, you'll reach for Float (Single if you are using […]
  • CSharp Numeric OverflowsCSharp Numeric Overflows Did you know that when you are dealing with numbers, by default, .NET will do, or try to do exactly what you tell it to do?  If you tell it to do the impossible, it will do the next […]
  • TDD Isn’t All About TestingTDD Isn’t All About Testing While the artifact of Test Driven Development is test code, what you get out of test driven development far exceeds the test themselves.  Maintainable Code By writing test first, […]
  • Upload a File via WebRequest Using CSharpUpload a File via WebRequest Using CSharp I got this question a couple of weeks ago but just never had the time to put into answering fully.  But today I have some extra time due to the fact that I’m under-booked with […]
  • C# “” better than string.Empty?C# “” better than string.Empty? I recently read an article that argued that “” is “Better than String.Empty” The argument is that since string.Empty doesn’t work in all situations, we should not use it at all.  He […]

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