Search code examples
code-contracts

Code Contract that Ensures that All Items in a Collection are the Same


How can I create a post-condition that ensures that all items in a collection are the same?

I was thinking of using this solution but I'm unsure whether that might cause some unwanted side-effects or if it would be a wrong use of code contracts.


Solution

  • The linked code appears to be side-effect free, so I wouldn't worry about that. I recommend putting the code that checks the all-equal condition into its own (pure) function, and simply calling that.

    Contract.Ensures(AllEqual(myEnumeration));
    

    This means that AllEqual need to be at least as visible as your method itself, but I think it will make everything cleaner.