FxCopContrib project and DoNotIgnoreResultOfImmutableMethods custom rule
Already a month ago I needed a place to store the code of the FxCop rules I was working on. I ended up at Codeplex, not only because they offer native TFS integration, but also because I hope others will join in on the effort.
As of this moment, the number of rule ideas is growing faster than the number of implemented rules, but some might argue that is a good thing :).
One of the rules I like most (and has dug up a few bugs in my other code already), is a rule which flags calls to methods on immutable types, but subsequently ignores the outcome.
A classic example of the bug this rule targets are lines like:
DateTime veryImportantValue = DateTime.UtcNow.Date; veryImportantValue.AddHours(15);
AddHours returns the new DateTime value of course, and the 15 hours are never added to the original variable.
To build this rule, I've used a few existing classes from the Microsoft FxCop version that ships with the Windows 7 and .NET 4 SDK. The problem I've found, is that almost all nice helper methods and classes are marked as internal. I didn't want to keep using Reflector to decompile these to source and include them in my own project, so instead I've opted to use Reflection to call into these hidden parts. It is really too bad Microsoft still hasn't chosen to make more of the FxCop tooling accessible to other developers. I also added TimeSpan and DateTimeOffset to the list of immutable types, I have no clue why Microsoft omitted them from the default list.
The full source for this rule can be found in the repository of the FxCopContrib project. Together with some more experimental stuff I've been working on with Wolfgang Kluge, a fellow MCC and Regex connoisseur.