Delegate example from C # in the depths of the confusion
I am considering this example:
List<Product> products = Product. GetSampleProducts() ;
products.Sort(
(first, second) => first.Name.CompareTo(second. Name)
) ;
foreach (Product product in products)
{
Console. WriteLine(product) ;
}
What function is actually called in the API when you do this? Does the compiler create a class that implements the IComparer interface?
I thought delegates were anonymous methods. There seems to be an anonymous interface implementation that is causing confusion.
source to share
The Sort method used here , which takes a delegate (a pointer to a method) as an argument (in this case Comparison <T> , which is a function with two arguments returning an integer).
Not to be confused with Sort , which accepts IComparer <T>; ... Contraty for Java, C # does not support native interface implementation (or whatever you call it).
source to share
Delegates are not anonymous. Your code seems to be creating a comparison delegate for (first, second) => first.Name.CompareTo(second. Name)
(which is itself an anonymous method).
source to share