“Operation could destabilize the runtime” caused by dynamic invoke.

Dynamically invoking code can sometimes mask errors that actually are pretty simple to fix. If you come across problems like this, it’s probably a good idea to try to reproduce the problem as close to the calling code as possible, in order to see the actual error message, instead of something generic like the title of this post.

Background & code

I encountered the somewhat surprising exception message above today, and couldn’t immediately figure out what the problem was. As any good developer would do, I asked Stack Overflow for help, and immediately found two different questions on related subjects. One of these had to do with a framework issue which can be fixed by updating .Net. The other question is a little older, but includes a variety of possible explanations for the exception, and it was one of these that put me on the right track to solve the problem in my case.

The accepted answer mentions incorrect use of covariance and contravariance as a possible source for exceptions like this. There was nothing in my code that aught to require either of these, but there was something else relying on the .Net type system, namely the use of a Delegate, and a call to DynamicInvoke():

I had recently changed the following signature:

public delegate void UpdatingDelegate(DateTime date, bool succeeded);


…into this:

public delegate void UpdatingDelegate(DateTime? date);

…while forgetting to update the actual call to a provided delegate:

_delegateToCallOnUpdate.DynamicInvoke(_selectedDate, someBoolValue);

Now if I called this code from the same project as it resided in, I received the following clear and meaningful exception:

System.Reflection.TargetParameterCountException was unhandled by user code
Message=Parameter count mismatch.

The problem was that I had this code in a separate project, which was only being referred as an external .dll. Using DynamicInvoke(..) obviously will not cause compilation errors here, precisely because it is dynamic. When running in the same project, Visual Studio was able to pinpoint the error at runtime instead of just throwing the cryptic exception message above.


Engage and contribute for the common benefit of mankind!

This site uses Akismet to reduce spam. Learn how your comment data is processed.