I’m trying to write a sorting method that would receive both the collection and the sorting strategy.
I could simply receive an IComparer but I would prefer to have an enumeration of possible sorting strategies. The callers would have to pick theirs from there.
Something like:
public enum SortingStrategies { ByAgeDesc, ByAgeAsc, ByIncomeDesc, ByInconmeAsc };
Each of those (ByAgeDesc, ByAgeAsc…) would be an IComparer.
Then calling the sorting method would be:
myObject.SortCollection(myCollection, SortingStrategies.ByIncomeDesc);
Is is possible to create an enum of instances? Is it a good idea?
Thanks in advance!
I wouldn’t use a straight enum for this. I’d create a bunch of
IComparer<T>implementations to pick from:… or quite possibly use composition to do the ascending/descending part (e.g. via an extension method on
IComparer<T>to create a reversing wrapper).Now this doesn’t force the caller to use one of your predefined values, of course. You could force it by using your own class:
Here the private constructor prevents any other subclasses, but the private nested classes can still subclass it as they have access to the constructor.
You can then make your method take a
SortingStrategyinstead of just anIComparer<T>.Of course, using LINQ may well be more flexible in the longer term, as James suggested. It depends on what your goals are.