I am learning generic types and wanted to create a generic QuickSort method, the problem is classes are not co-variant and code cannot compile. the problem is making the Par
What you're looking for is to constrain T
to any type that implements IComparable
This MSDN article nicely explains generic constrains in C#. Your method declaration will look like this:
public static T Partition(T[] array, int mid)
where T : IComparable
{
//code goes here
}
public static void QuickSort(T[] array, int lower, int upper)
where T : IComparable
{
//code goes here
}
It might also be helpful to link you to the MSDN article for IComparablearray[midPoint].CompareTo(array[upperBound]) > 0
. All the comparison operators are the same if you check the result of CompareTo against 0.
And a small side note, when you call Swap
, the compiler can infer the type as int
and you can simply call it as Swap(...
.