Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Attribute Exception with Code Contracts

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.

like image 585
photo_tom Avatar asked Jan 04 '11 15:01

photo_tom


2 Answers

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");
like image 105
Mark H Avatar answered Sep 20 '22 20:09

Mark H


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"); 
like image 41
AbstractLabs Avatar answered Sep 21 '22 20:09

AbstractLabs