"Common Language Runtime detected an invalid program" - InvalidProgramException - When your application has a really large method.

If you've written a whole bunch (and I mean a really big WHOLE bunch) of code inside a method, constructor or the like, there is a good chance you'll see this exception.

We had an application that would generate an Assembly using CodeDom based on certain parameters. The parameter list for one scenario got so huge that the app generated a class with a constructor with 39,000 lines of code. When we tried instantiating an object of this class our app would just crash with a "Common Language Runtime has detected an invalid program" - InvalidProgramException.

PEVerify.exe would not return any errors (and say that the IL is just fine) but when you try and run NGEN.exe it would fail at that gigantic method.

So the problem is with the JIT compiler. There is a limitation on the number of local variable the JIT compiler in the CLR can handle for .NET 2.0 - which was restricted to a max of 32767 (which includes the local used by the JIT itself as well). So once in a blue moon with a GIGANTIC method that you just can't do with out for some strange reason will give you this Exception. This problem is documented in KB (I would like to point out that this is not the only scenario in which the CLR would throw the InvalidProgramException, this is one of the reasons you'd see it).

There is a Hotfix available for this problem now which increases the limit of local variables from 32767 to 4 million. The problem (and hence the reason for this blog entry) is that KB 919514 (https://support.microsoft.com/?kbid=919514), which is related to the Hotfix doesn't seem related at all from the description. And the KB that does sound related KB 312544 (https://support.microsoft.com/kb/312544 - problem #3) doesn't speak of the Hotfix. Our appologies for this confusion - I've written an email to the content team to resolve this documentation issue.

Till then please read KB 919514 and contact PSS for the Hotfix. This fix has already been branched into the Orcas release.

 UPDATE (29/12/2006) : I just got a notification that the content team has updated KB 312544 to reflect the availability of the Hotfix.