An easy way to count the lines of code using reflection

advertisements

I need a (very rough) estimation on the lines of code (none-blank, none-comment) of an .net Assembly (c#). Is there an easy way to do this using reflection?

I would prefer a hand-written tool (so I am asking about pointers here...) but I would also settle with a free (as in speech) tool.

The following is my use-case:
I am part of a team, on a not-so-large project having virually no code coverage. We have a report on the coverage which states about 60% coveage (talking about unit-test here.) but this report does not display assemblies that have no unit-tests at all.
So to get the report anywhere near correct I thouhgt I write a small tool that could be called for every assembly without unit-tests (I can find those) and produce an xml like the one produced by our coverage-tool stating that nothing was coverd. As a first approximation for "statements" I thought I count "lines of code".


You can't count lines of code using reflection. This information is not available using reflection. Using reflection you can get the signature of class members and you can get the raw IL inside those methods. There is however no way you can effectively translate that IL back to lines of code.

There are several ways to do this. You could (ab)use a tool such as Reflector and call its assemblies programmatically to decompile your assemblies back to C# and do some line counting, or you can harvest information from the .pdb files to get the line numbers. Those program database files contain all that information. There is however no way of reading pdbs using reflection.

NDepend (the tool Gerrie mentioned) uses information from the .pdb files to count number of lines.

But since you are already using a code coverage tool, why don't you add empty unit test projects for the uncovered assemblies and add those test projects to your code coverage tool. This way you can see the total coverage of the whole project. That would be cheaper than buying NDepend and much cheaper than handwriting a LoC counter yourself.