Home > Code Analysis > Code Issues for anonymous methods and lambda expressions

Code Issues for anonymous methods and lambda expressions

October 31st, 2011

We already reviewed the refactorings for anonymous methods and lambda expressions and know how to deal with these language structures. Now its time to review what Code Issues for anonymous methods and lambda expressions CodeRush Pro provides.

Delegate can be replaced with lambda expression

Cause:

Lambda expressions are simply an improvement to the syntax of anonymous methods. This code issue suggests you that the anonymous method can replaced with a lambda expression.

Sample:

Refactor! Delegate can be replaced with lambda expression

How to fix:

  • If you prefer lambda expressions, you can convert an anonymous method to a lambda expression by executing the Compress to Lambda Expression code fix for this issue, which may improve code readability:

CodeRush Delegate Can Be Replaced With Lambda Expression Fix Preview

Resulting code:

Refactor! Compress to Lambda Expression result

ForEach Action can be called

Cause:

This code issue suggests that the code block of the List iteration can be converted to an anonymous method which can be passed as the Action delegate to the List.ForEach method. This may improve code readability.

Sample:

CodeRush ForEach action can be called

How to fix:

CodeRush Introduce For Each Action Fix Preview

Resulting code:

Refactor! Introduce ForEach Action result

Anonymous method cannot have ‘params’ parameter

Cause:

When the anonymous method contains a ‘params’ parameter, you will see an error in the code editor, because this is a violation of the programming language specification.

Sample:

CodeRush Anonymous method cannot have params parameter

How to fix:

  • Remove the incorrect ‘params’ parameter:

CodeRush Anonymous Method Cannot Have Params Parameter Fix

Lambda expression cannot have ‘params’ parameter

Cause:

This is the same language specification violation as the previous code issue. You will see an error, because lambda expressions must have an unchanging number of parameters and cannot have a ‘params’ parameter.

Sample:

CodeRush Lambda Expression Cannot Have Params Parameter Preview

How to fix:

  • Remove the incorrect ‘params’ parameter:

CodeRush Lambda Expression Cannot Have Params Parameter Fix Result

Lambda parameter has redundant type specification

Cause:

The type specifier to the lambda expression parameter is redundant and can be removed. Removing a redundant type specification may improve code readability.

Sample:

CodeRush Lambda Parameter Has Redundant Type Specification Preview

How to fix:

CodeRush Lambda Parameter Has Redundant Type Specification Fix

—–
Products: CodeRush Pro
Versions: 12.1 and up
VS IDEs: any
Updated: Nov/12/2012
ID: C140

Similar Posts: