Code Contract Runtime error message

317 Views Asked by At

How can I solve this problem by using Code contracts:

private string SomeMethod(string code)
{   
    var msg = "Invalid blabal " + code;
    Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()), msg);
}

Error:

User message to contract call can only be string literal, or a static field, or static property that is at least internally visible.

EDIT: I saw this information as you use contracts with similar use case

2

There are 2 best solutions below

0
On

All of the contract methods have overloads that take a string in addition to the boolean condition:

The user-supplied string will be displayed whenever the contract is violated at runtime.

It must be a compile-time constant.

So It must be:

Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()), "YOUR MASSAGE");
0
On

The documentation say that: (page 13)

2.10 Overloads on Contract Methods

All of the contract methods have overloads that take a string in addition to the boolean condition:

Contract.Requires(x != null, "If x is null, then the missiles are red!");

The user-supplied string will be displayed whenever the contract is violated at runtime. Currently, it must be a compile-time constant.

Your variable msg is obviously not a compile-time constant.
So instead, this will work:

Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()), "Invalid code");