Search code examples
c#c#-4.0code-contractsmicrosoft-contracts

Why am I getting malformed contract, in by C# code?


Visual Studio shows an error when I write this contract below.

Error 20 Malformed contract section in method '....get_Page'

Is the problem with the if block?

public int? Page
{
  get
  {
    int? result = Contract.Result<int?>();

    if (result != null)
        Contract.Ensures(result >= 0);

    return default(int?);
  }
}

EDIT:

Lasse V. Karisen has posted in comments:

How about: Contract.Ensures(result == null || result >= 0); ?

Yes Karisen, I've tried this before and it compiles. But the question remains: isn't it possible to have ifs when using contracts?

Another problem I'm having is clueless (mainly considering the example above works), involves the use of result also:

public int IndexOf(T item)
{
    Contract.Assert(item != null);
    Contract.Assert((item as IEntity).ID > 0);

    int result = Contract.Result<int>();
    Contract.Ensures(result >= -1);

    return default(int);
}

Solution

  • Just having a guess. Perhaps it should be Contract.Ensures(result.Value >= 0)?