Search code examples
c#code-metrics

Free C# metrics calculation library (DLL)


I wanted to ask whether you know about some free C# libraries (dlls) that calculate CK metrics (mainly Cyclomatic Complexity).

I would need that for a project I'm planning to do. I know that there are already some finished solutions that calculate CK metrics and display it to you in various forms, but what I would need is one that I could use from within my application. So before starting and writing one myself I first wanted to ask you.

Thanks


Solution

  • DrivenMetrics is a open source C# command line tool. The core functionalities are isolated from the command line console client as a library (Core project is available here).

    Even if quite simple, it may fit your need: it's free, counts the the number of lines and calculates the cyclomatic complexity (number of potential code paths) of methods.

    This is performed through direct analysis of the IL thanks to Mono.Cecil (the same library NDepend relies on). This allows the analysis to be performed on assemblies built from code written in C#, VB.Net,...

    • The project has been announced here.
    • The code source is available on github.
    • A packaged release is also available.
    • It works both on Windows and Mono.

    UPDATE:

    Another option would be the amazing Gendarme, a static analysis tool from the Mono project.

    As a sample of usage, the code below display the cyclomatic complexity of every method in an assembly.

    ModuleDefinition module = ModuleDefinition.ReadModule(fullPathToTheAssembly);
    
    foreach (var type in module.Types)
    {
        foreach (var me in type.Methods)
        {
            if (!me.HasBody || me.IsGeneratedCode() || me.IsCompilerControlled)
                continue;
            var r = AvoidComplexMethodsRule.GetCyclomaticComplexity(me);
    
            Console.WriteLine("{0}: {1}", me.ToString(), r);
        }
    }
    • The project is described here
    • The code source is available on github
    • Packaged releases are also available
    • It works both on Windows and Mono