Skimming through a book about .NET C#, I was attracted to its language features different from C/C++. Delegate is a known feature from JAVA series language which draw my attention when I skip-read this C# book. Here I will talk something which I comprehend from "delegation". I will not give a demonstration only "what can delegate do", but this demonstration is also "you can hardly compose this class without delegate" :
static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison)
class BubbleSorter
{
static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison)
{
bool swapped = true;
do
{
swapped = false;
for (int i = 0; i < sortArray.Count - 1; i ++)
{
if (comparison(sortArray[ i + 1 ], sortArray[ i ]))
{
T temp = sortArray[ i ];
sortArray[ i ] = sortArray[ i + 1 ];
sortArray[ i + 1 ] = temp;
swapped = true;
}
}
} while (swapped);
}
}
It's a Class of Generic which is a Class of algorithm bubbleSort. To use this class, we gotta define another class, which in case a phone company as a employee list, and he wants it sorted by their salary.
class Employee
{
public Employee(string name, decimal salary)
{
Name = name;
Salary = salary;
}
public string Name { get; }
public decimal Salary ( get; private set; }
public override string ToString() => $"{Name}, {Salary:C}";
public static bool CompareSalary(Employee e1, Employee e2) => e1.Salary < e2.Salary;
}
We have to define the "bool CompareSalary" with 2 parameters "Employee e1" and "Employee e2" to match the signature of Func<T, T, bool>
Now it's time to client code:
using static System.Console;
namespace Wrox.ProCSharp.Delegates
{
class Program
{
static void Main()
{
Employee[ ] employee =
{
new Emplyee ("Richy Ortiz", 15000),
new Emplyee ("Nuckle Du", 25000),
new Emplyee ("Justin Wong", 30000)
};
BubbleSorted.Sort( employees, Employee.CompareSalary);
foreach (var employee in employees)
{
WriteLine(employee);
}
}
}
}
We finally sorted the list by salary cuz of we used Func<T, T, bool> and generic, which let us compare between object(more than just between a default type).
"Func<T, T, bool>" is kinda delegate without the key word "delegate".