|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
Anonymous Methods and Code Analysis
An anonymous method is just a method that has no name. Anonymous methods are most frequently used to pass a code block as a delegate parameter.
This topic explains how Code Analysis handles warnings and metrics that are associated with anonymous methods.
Warnings and metrics for an anonymous method declared as an inline assignment to a field are associated with the constructor. If the field is declared as static (Shared in Visual Basic), then the warnings and metrics are associated with the class constructor; otherwise, they are associated with the instance constructor.
A class could contain an inline anonymous method that assigns a value to a field that has multiple constructors. In this case, warnings and metrics are associated with all the constructors unless that constructor chains to another constructor in the same class.
Even though this might seem unexpected, this occurs because the compiler outputs a unique method for every constructor that does not chain to another constructor. Because of this behavior, any violation that occurs within anonymousMethod, must be suppressed separately. This also means that if a new constructor is introduced, warnings that were previously suppressed against Class(int) and Class(string) must also be suppressed against the new constructor.
You can work around this issue in one of two ways. You could declare anonymousMethod in a common constructor that all constructors chain. Or you could declare it in an initialization method that is called by all constructors.