0

For university I must learn how to deal with Code Contracts in C#.

I want to use it for this method which should return the smallest Element in the Array:

public int minarray(int[] minarray)

Here is what I got but I have no idea whether this is correct:

public int minarray(int[] minarray)
{
    //Neither the array should be empty nor null
    Contract.Requires(minarray != null && minarray.Length != 0);
    //Save the result...
    int result = Contract.Result<int>();
    //...and check:
    Contract.Ensures(Contract.ForAll(0, minarray.Length, i => minarray[i] >= result)); 
}

Can anyone tell me if this is right or if I just wrote completely nonesense? I'd be so thankful.

Beyond that, the next task says:

public int[] posnegarray(int[] posneg)

This should change the sign of all elements in the method (e.g from (1, -2,3) to (-1,2, -3).

public int[] posnegarray(int[] posneg)
{
    //Neither the array should be empty nor null
    Contract.Requires(posneg != null && posneg.Length != 0);
    //Save the result...
    int resarray = Contract.Result<int[]>();
    //...and check:
    Contract.Ensures(Contract.ForAll(0, posneg.Length, i => posneg[i] == (-1) * resarray[i] )); 

    int[] returnarray = new int[posneg.Length];
    for(int j = 0; j < posneg.Length; j++)
      returnarray[j] = posneg[j] * (-1);
    return returnarray;
}

Can this be correct?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
今天春天
  • 941
  • 1
  • 13
  • 27

1 Answers1

0

Contract.Result should only be used within a Contract.Ensures method where it isn't actually executed but just represents the result. The way that you are using it will execute the method, which will return default (for int it will be 0) and then use that default in your Ensures method which probably isn't what you were expecting. You should put the Result method within the ensures like this:

Contract.Ensures(Contract.Result<int>() >= -1);
TomDoesCode
  • 3,580
  • 2
  • 18
  • 34