I'm getting an exception when I use code contracts on the following code:
public void Debug(
dynamic message1,
dynamic message2 = null,
dynamic message3 = null,
dynamic message4 = null,
dynamic message5 = null,
dynamic message6 = null)
{
Contract.Requires(message1 != null,
"First Logged Message cannot be null");
}
I'm trying to configure the project settings so that the checks are done at run time.
The exception is "Cannot dynamically invoke method 'Requires' because it has a Conditional attribute". I've re-read the Code Contracts documentation a couple of times and done some searches, but I do not understand where the conditional attribute is coming from.
The conditional attribute on the Requires method is Conditional("CONTRACTS_FULL")
. When you build with contracts turned on, the CONTRACTS_FULL symbol is passed to the compiler. I assume the reason you can't use dynamic dispatch with conditional methods, is because they're compiled during runtime, and the runtime has no way of passing these symbols to the compiler. (Just a guess).
You can probably solve it really easy by assigning message1 to a local (non-dynamic) variable, perhaps an object.
object m1 = message1;
Contract.Requires(m1 != null, "First Logged Message cannot be null");
I ran in to the same issue instead of creating a variable assignment I was able to cast the dynamic to an object in the requires condition argument.
dynamic message1;
Contract.Requires((object)message1 != null,"First Logged Message cannot be null");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With