I am also not well aware of the details but had the same thing with custom classes a while ago. If you debug it (by encapsulating the casting in a try/catch), it shows that it has to do something with the way the .dlls are loaded. I think one time the .dll is loaded directly from Grasshopper (in the parameter container) and the other time referenced when compiling the C# script. I guess the objects are then not recognized as being of the same type (as they technically come from different .dlls), thus the casting fails.
But I think @DavidRutten should be able to explain this better, I would also be interested