Suppose a method has been written that expects a sorted list as one of its input. Of course this will be commented and documented in the code, param will be named "sortedList" but if someone forgets, then there will be a bug.
Is there a way to FORCE the input must be sorted? I was thinking about creating a new object class with a list and a boolean "sorted", and the passed object has to be that object, and then the method checks immediately if the "sorted" boolean is true. But I feel like there must be a better/standard way.
*This method is called in a loop, so don't want to sort inside the method.
Assuming that you only need to iterate this collection, and not perform any other operations, you can accept an IOrderedEnumerable
, which would require that the sequence have been ordered by something. (Keep in mind that doing this may mean that it was sorted based on some other criteria than what you expected, so it's still possible that by the criteria you're using internally, the data is no sorted.)
The other option that you have is to simply sort the data after you receive it, instead of requiring the caller to sort the data. Note that for most common sorting algorithms sorting an already sorted data set is its best case speed (Typically O(n) instead of O(n*log(n))), so even if the data set is sometimes already sorted and sometimes not it's not necessarily terrible, so long as you don't have a huge data set.