We have this code, sortof:
private void InitializeEvents()
{
this.Event1 += (s,e) => { };
this.Event2 += (s,e) => { };
this.Event3 += (s,e) => { };
this.Event4 += (s,e) => { };
this.Event5 += (s,e) => { };
this.Event6 += (s,e) => { };
this.Event7 += (s,e) => { };
this.Event8 += (s,e) => { };
this.Event9 += (s,e) => { };
this.Event10 += (s,e) => { };
this.Event11 += (s,e) => { };
this.Event12 += (s,e) => { };
this.Event13 += (s,e) => { };
}
Code analysis in VS10 Ultimate says “cyclomatic complexity of 27”. Removing one of the lines makes the cyclomatic complexity 25.
There’s no branching going on, so how is this possible?
Remember that the Code Analysis is looking at the IL in your assembly, not your source code. There is nothing in the IL that natively supports lambda expressions, so they are a construct of the compiler. You can find the specifics of what is output here. But basically your lambda expression is turned into a private static class that is an anonymous delegate. However, rather that create an instance of the anonymous delegate every time it is referenced in code, the delegate is cached. So each time you assign a lambda expression, it does a check to see an instance of that lambda delegate has been created, if so it uses the cached delegate. That generates an if/else in the IL increasing the complexity by 2. So in this functions complexity is 1 + 2*(lambda express) = 1 + 2 *(13) = 27 which is the correct number.