Reputation: 3035
I am fairly new to code contracts so i may have just done something stupid here :)
I am getting the error
Detected expression statement evaluated for potential side-effect in contracts of method '##'. (Did you mean to put the expression into a Requires, Ensures, or Invariant call?)
I have the following contracts
Contract.Requires<ArgumentNullException>(obj != null);
Contract.Requires<ArgumentNullException>(obj.Id != null);
It is failing on the second contract obj.Id != null
(Id
is a Guid
)
Now it is possible for Id
to be null
which isn't allowed in the method. But code contracts raises the above compile error. The method it self doesn't actually return anything so needs no ensures either.
I have removed the contract so I can compile and placed a standard if
check. But what is causing this?
Upvotes: 3
Views: 341
Reputation: 109577
You need to mark the Id property itself as [Pure]
That will tell the Code Contracts Analyser that it has no side-effects.
Code Contracts don't like you calling methods that have side-effects; your code would behave differently depending on whether you had Code Contract checking enabled or not, which would be A Bad Thing.
Example:
public Guid Id
{
[Pure]
get
{
return _id;
}
}
One further point: How can it be possible for Id
to be null if it's a Guid? A Guid is a struct, therefore it can't be null. Is it possibly a nullable Guid (i.e. Guid?
) ?
Upvotes: 2