-1

How to implement input parameter sorted precondition enforcement?

1 Answers1

1

A bit of code would help us all with helping you.

I'll assume you have a method along the lines of this..

public void MyMethod(params string[] list) {...}

and you want to use Code Contracts to ensure that this method will only ever be called with a sorted list. Did you try something like the following for the body?

Contract.Requires(list.OrderBy(s => s).SequenceEquals(list));
Gaute Løken
  • 7,522
  • 3
  • 20
  • 38
  • Might be better to use an [IsSorted()](https://github.com/colgreen/Redzen/blob/master/Redzen/Sorting/SortUtils.cs) method unless the sort being used by Linq guarantees that items won't be moved if already sorted (which it might do even if it's not a stable sort algorithm more generally). It's also likely that an IsSorted() method would be more efficient. – redcalx Sep 26 '17 at 16:47
  • @redcalx Sure, if you're ok with adding another dependency to your project or writing your own optimized implementation for such a thing, you can surely optimize. Though, the question asks for effective, not efficient, so we should keep Donald Knuth in mind. ;) – Gaute Løken Sep 27 '17 at 11:11
  • Performance aside, the other point about correctness stands; i.e. the sequences may both be sorted but not equal. – redcalx Sep 27 '17 at 12:16
  • @redcalx If you're worried that .OrderBy(..) will modify the list, that won't happen. Each step produced by linq will create a new enumerable. I'm sufficiently sure the assurances of this exist that I won't bother looking them up. Maybe some fringe linq driver will do that, but then it will surely be violating the spec. – Gaute Løken Sep 27 '17 at 12:47