Tuesday, June 2, 2009

Microsoft FxCop doesn't like Microsoft generated code!

The other day I thought it might be nice to "do the right thing" and give my code a run against Microsoft's FxCop.

I ran it right out of the box - I didn't bother making my own rules or changing the defaults. I was bored. Anyway, here's one of the results that actually made be chuckle once I read it carefully:
Warning, Certainty 90, for DoNotInitializeUnnecessarily
{

Target : #.ctor() (IntrospectionTargetMember)
Location : <735>> (String)
Resolution : "'MyDocument.New()' initializes field 'MyDocument.disposedValue'
of type 'Boolean' to false. Remove this initialization
because it will be done automatically by the runtime."

Help : (String)
Category : Microsoft.Performance (String)
CheckId : CA1805 (String)
RuleFile : Performance Rules (String)
Info : "Do not make initializations that have already been
done by the runtime."
Created : 3/6/2009 6:58:21 PM (DateTime)
LastSeen : 3/6/2009 8:36:25 PM (DateTime)
Status : Active (MessageStatus)
Fix Category : NonBreaking (FixCategories)

}

The reason for the chuckle was that the code which triggered this violation of the rule was written by the Microsoft IDE! My role in this infraction was really quite simple: I typed "Implements IDisposable" and hit Enter. The IDE was "nice" enough to plugin the rest for me:

' To detect redundant calls
Private disposedValue As Boolean = False

' IDisposable
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
Array.Clear(mDocumentContent, 0, mDocumentContent.Length)
End If
End If
Me.disposedValue = True
End Sub

It's bad enough that the IDE writes code for me without prompting, but maybe the FxCop team should talk to the IDE team to avoid such embarrassing nuisances (I had dozens of similar warnings to weed through) in the future.

According to the Code Analysis Team, this is the new default for FxCop 1.36.

Here's how to avoid it:

Using an FxCop project:
  1. Open your FxCop project in FxCop
  2. Choose Project -> Options -> Spelling & Analysis
  3. Check Suppress analysis results against generated code
  4. Click OK

OR, if you prefer the command-line:
  1. Pass the /ignoregeneratedcode switch, for example:

FxCopCmd.exe /file:MyAssembly.dll /out:AnalysisResults.xml /ignoregeneratedcode

No comments:

Post a Comment