Cyclomatic Complexity in C#: How to Spot and Refactor Risky Methods

Cyclomatic Complexity in C#: How to Spot and Refactor Risky Methods

Cyclomatic Complexity counts the independent execution paths through a C# method—one plus each branching construct. Thomas McCabe recommended a limit of 10, while Microsoft's CA1502 analyzer flags anything over 25. This guide shows how to calculate it, why a score of 8 means at least eight tests, and how tools like NDepend and Visual Studio can track complexity, coverage, and the CRAP score to keep legacy code from becoming a bug magnet.

The real risk is not the static score, it is what happens when those methods start growing.
  1. bunderbunder

    Overall cyclomatic complexity is a useful metric, but it does have one shortcoming when used with modern languages: it was invented before polymorphism really became a thing.

    That means that it really only counts explicit branching. So, for example, in an OO language like C#, calling a virtual method doesn’t increment cyclomatic complexity even though the method invocation could go down many code paths. Potentially thousands if you’re dealing with a common interface like IEnumerable. If you’re working on a library then the number of potential code paths in this kind of situation is unbounded.

    As an aside, it’s interesting to think how it might apply to a language like Smalltalk that doesn’t even have if or switch statements.

    OO isn’t the only monkey wrench, either. Higher-order functions also introduce forms of branching that cyclomatic complexity doesn’t measure.

    Again that doesn’t make it a useless metric. Just don’t think that a cyclomatic complexity limit in your codebase is some sort of maintainability panacea. Some of the least comprehensible functions I’ve deciphered had quite low cyclomatic complexities.

  2. throwyawayyyy

    Fun story: at my previous aaaawful company CC was discovered as a thing to care about at about the same time as PMs and managers were encouraged to land code changes using the _then_ quite terrible AI tooling (this was a year or two ago). Cue an avalanche of completely unreviewable diffs.

  3. runningmike

    From a security perspective cc is highly relevant. I use it to get a solid rating of the security aspects of Python code. I use [1] which is solid and proven.

    [1] https://nocomplexity.com/documents/codeaudit/complexitycheck...

More from this day

2026-09-18