How to work with static anonymous functions in C# 9


Anonymous functions were introduced in the C# programming language long ago. Although anonymous functions have many benefits, they are not cheap. Avoiding unnecessary allocations matters, and this is why static anonymous functions were introduced in C# 9. In C# 9 lambda or anonymous methods can have a static modifier.

This article talks about static anonymous functions and why they are useful, using code examples to illustrate the concepts. To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create a console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Create.

This will create a new .NET Core console application project in Visual Studio 2019. We’ll use this project in the subsequent sections of this article. 

Anonymous methods are not cheap

As I said, anonymous methods are not cheap. You have overheads of invocation of delegates. For example, if your lambda captures the local variable or parameter of the enclosing method, you would have two heap allocations — one allocation for the delegate and a second for the closure. Or if your lambda captures just an enclosing instance state, you would incur just a delegate allocation and hence one heap allocation. If your lambda doesn’t capture anything, or captures only static state, you would incur 0 heap allocations.

Let’s understand this with an example. Consider the following code snippet, which illustrates how unintentional allocation might occur in your code.

Copyright © 2021 IDG Communications, Inc.



Source link