Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SE106X - Force parameters properties and fields to hold static lambdas/methods #7

Merged
merged 6 commits into from
Oct 4, 2024

Conversation

ShaharPrishMSFT
Copy link
Owner

Code quality: Warn against using non-static lambdas (SE106X)

For performance-sensitive code, it's sometimes useful for the developer to prevent misuse of a method or class to protect the developer.

Using the [UseStaticLambda] on a field, property or parameter will cause the analyzer to emit a warning if a non-static lambda is passed in.

public ref struct MyOptimizedNonAllocUtility
{
	public MyOptimizedNonAllocUtility([UseStaticLambda] Func<int> myDelegate)
	{
		_myDelegate = myDelegate;
	}
}

// Code using the struct
var s = new MyOptimizedNonAllocUtility(() => 42); // This will emit SE1060

// Fixed code:
var s = new MyOptimizedNonAllocUtility(static () => 42); // This will emit SE1060

SE1060/SE1061

What it looks for: Passing in non-static delegates to methods that expect to get a static.

Why: For performance-sensitive code that uses delegates, it's easy to sometimes forget that creating a capturing delegate can be expensive. This will remind the developer to use a delegate that will not allocate or allocate less.

How it helps engineers: Reduces the chance of making such mistakes.

@ShaharPrishMSFT ShaharPrishMSFT merged commit 578aee0 into main Oct 4, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant