How to implement input parameter sorted precondition enforcement?
1 Answer
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));
-
Might be better to use an IsSorted() 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.– redcalxSep 26, 2017 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. ;) Sep 27, 2017 at 11:11
-
Performance aside, the other point about correctness stands; i.e. the sequences may both be sorted but not equal.– redcalxSep 27, 2017 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. Sep 27, 2017 at 12:47