Exclude Anonymous Types in NDepend

dotnet, ndepend comments edit

NDepend is awesome and I use it to analyze all sorts of different projects.

One of the nice things in NDepend is you can define queries that help qualify what is your code (JustMyCode) and what isn’t (notmycode).

I’ve seen two challenges lately that make rule analysis a bit tricky.

  • async and await: These generate state machines on the back end and NDepend always flags the generated code as complex (because it is). However, you can’t just exclude the code because basically the generated state machine moves your code in there, so excluding the state machine will exclude some of your code.
  • Anonymous types: I see these a lot in MVC code, for example, where the anonymous type is being used as a dictionary of values to truck around.

I haven’t figured out the async and await thing yet… but here’s how to exclude anonymous types from the JustMyCode set of code:

First, in the “Queries and Rules Explorer” window in your project, go to the “Defining JustMyCode” group.

Defining JustMyCode

In there, create a query like this:

// <Name>Discard anonymous types from JustMyCode</Name>
from t in Application.Types where
select new { t, t.NbLinesOfCode }

Save that query.

Now when you run your code analysis, you won’t see anonymous types causing any violations in queries.