C# using function pointers
//Function Pointers for are a feature to be implemented in c# 9. Currently the above examples are from
//the specification documentation on that, it is to add access for the ldftn and calli IL Opcodes per the documentation at
//https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/function-pointers.
//Currently C# does support delegates, and function pointers or function delegates but they are slightly different.
//Function Pointers must have a return type i.e. no void.
//Function Pointers hold one function reference at runtime.
//Function delegate includes zero or more(max 16) input arguments and 1 out put argument.
//Delegates can have any return type.
//Delegates can hold multiple method references or method addresses at runtime
//Delegates do no need any arguments.
//The signature is as follows.
public delegate TResult Func<in T,out TResult>(T arg);
//Example usage in code is as follows:
// Declare a Func variable and assign a lambda expression to the
// variable. The method takes a string and converts it to uppercase.
Func<string, string> selector = str => str.ToUpper();
// Create an array of strings.
string[] words = { "orange", "apple", "Article", "elephant" };
// Query the array and select strings according to the selector method.
IEnumerable<String> aWords = words.Select(selector);
// Output the results to the console.
foreach (String word in aWords)
Console.WriteLine(word);
/*
This code example produces the following output:
ORANGE
APPLE
ARTICLE
ELEPHANT
*/
//Related to this is the action delegate which is also very powerful:
//The signature is as follows.
public delegate void Action<in T>(T obj);
List<String> names = new List<String>();
names.Add("Bruce");
names.Add("Alfred");
names.Add("Tim");
names.Add("Richard");
// Display the contents of the list using the Print method.
names.ForEach(Print);
// The following demonstrates the anonymous method feature of C#
// to display the contents of the list to the console.
names.ForEach(delegate(String name)
{
Console.WriteLine(name);
});
void Print(string s)
{
Console.WriteLine(s);
}
/* This code will produce output similar to the following:
* Bruce
* Alfred
* Tim
* Richard
* Bruce
* Alfred
* Tim
* Richard
*/
//Note: You can use the Action<T1,T2> delegate to pass a method as a parameter without explicitly declaring a custom delegate.