djsleurink.Analyzers.MethodGroupAnalyzer 1.0.0

dotnet add package djsleurink.Analyzers.MethodGroupAnalyzer --version 1.0.0
NuGet\Install-Package djsleurink.Analyzers.MethodGroupAnalyzer -Version 1.0.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="djsleurink.Analyzers.MethodGroupAnalyzer" Version="1.0.0">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add djsleurink.Analyzers.MethodGroupAnalyzer --version 1.0.0
#r "nuget: djsleurink.Analyzers.MethodGroupAnalyzer, 1.0.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install djsleurink.Analyzers.MethodGroupAnalyzer as a Cake Addin
#addin nuget:?package=djsleurink.Analyzers.MethodGroupAnalyzer&version=1.0.0

// Install djsleurink.Analyzers.MethodGroupAnalyzer as a Cake Tool
#tool nuget:?package=djsleurink.Analyzers.MethodGroupAnalyzer&version=1.0.0

Analyzer: Method groups used within iterators

Analyzer that detects unnecesary memory allocation caused by the usage of method groups and provides possible solutions to fix this issue.

The issue is fixed as of .NET 7.0 so the analyzer will not be used in projects targeting .NET 7.0 or higher.

This analyzer is applicable to:

Method groups of type System.Action and System.Func (and all it's generic variations)

The issue:

When using a method group inside an iterator a new instance of the System.Action or System.Func type will be created on every iteration.

C#:

for (int i = 0; i < 100_000; i++)
{
    doSomething(something);
}

Intermediate language:

for (int i = 0; i < 100000; i++)
{
    doSomething(new Action(something)); //a System.Action object is created on every iteration
}

Solution 1:

Declare a local variable outside of the loop

var methodGroupVariable = new Action(something);
for (int i = 0; i < 100000; i++)
{
    doSomething(methodGroupVariable);
}

Solution 2 (only available when using C# 9.0+ and target framework < .NET 7):

Declare a static lambda expression

for (int i = 0; i < 100000; i++)
{
    doSomething(static () => { something(); } );
}

Example:

alternate text is missing from this package README image

There are no supported framework assets in this package.

Learn more about Target Frameworks and .NET Standard.

This package has no dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.0 1,833 8/27/2023

Initial release.