I read in this article that delegates
are late binding
mechanism, but this SO answer and this SO answer are stating that this is not the case.
If I have this code sample where I try to pass different different delegate
to my Sort
method at runtime, is this a late binding ?
To me it seems like passing a reference to a delegate instance is not a late binding mechanism, because this is a just normal(not 100% sure about that) reference like any other reference to an instance of an object. Is this correct ?
delegate int Comparer(int x, int y);
class Program
{
static void Main(string[] args)
{
Comparer comparer;
var key = Console.ReadLine();
if (key == "asc")
{
comparer = (x, y) => x.CompareTo(y);
}
else
{
comparer = (x, y) => -x.CompareTo(y);
}
ListSorter myList = new ListSorter(ListGenerator.RandomList(size: 25));
myList.Sort(comparer);
}
}
class ListSorter
{
private List<int> _list;
public ListSorter(IEnumerable<int> list)
{
this._list = new List<int>(list);
}
public void Sort(Comparer comparer)
{
QuickSort(comparer, 0, this._list.Count - 1);
}
private void QuickSort(Comparer comparer, int left, int right)
{
if (left >= right)
{
return;
}
int partition = Partition(comparer, left, right);
QuickSort(comparer, left, partition - 1);
QuickSort(comparer, partition + 1, right);
}
private int Partition(Comparer comparer, int left, int right)
{
int s = left - 1;
int c = left;
int p = this._list[right];
while (c < right)
{
if (comparer(this._list[c], p) < 0)
{
s++;
Swap(s, c);
}
c++;
}
s++;
Swap(s, right);
return s;
}
}