"Common Language Runtime detected an invalid program"

If you've ever gotten this error you've probably been one of the most confused people in the world. In your debugging you may have seen that this message came from an InvalidProgramException.

Well, while this problem should be rare, here's an example harness of where you may see it.

// ThrowerHarness.cs
namespace ThrowerExample
{
  class ThrowerHarness
  {
    static void Main(string[] args)
    {
        try
        {
            Thrower.Start( );
        }
        catch (System.Exception ex)
        {
            System.Console.Write("Error: " + ex.Message);
        }
      }
    }
}

Alright, so where's it coming from?

In this case, it's actually coming from the IL.

// Thrower.il
.assembly ThrowerLib { }

.class public Thrower {
  .method static public void Start( ) {
    stloc.0
    throw
    ret
  }
}

This actually comes from invalid IL. In this case I'm putting 0 on the stack and then throwing...well, nothing really. This is not something a good compiler would create. If you see this it's probably a bug in the compiler or manually written IL.

Anyhow, to test the above do this...

ilasm /dll ThrowerLib.il
csc /r:ThrowerLib ThrowerHarness.cs