The function pointer is used to store the reference of the method. The pointer is similar to delegate in C#, but it has some differences from the delegate.
Difference between function pointer and delegate:
Function pointer | Delegate |
1.Function pointer should have return type except “void” | 1. Delegate can have any return type. |
2. It has capable to hold one function reference at a time. | 2. It can hold multiple method reference at time. |
3. The pointer method should has at least one argument | 3. It is not necessary to has any arguments. |
Syntax of Function Pointer:
- public delegate TResult Func<[in T,…], out TResult>(
- T arg
- )
We can pass any number of parameters in Function pointer. It is optional, but we should have the non-void return type.
Example:
- class Program
- {
- static Func<string,string> FunctionPTR = null;
- static Func<string,string, string> FunctionPTR1 = null;
-
- static string Display(string message)
- {
- Console.WriteLine(message);
- return null;
- }
-
- static string Display(string message1,string message2)
- {
- Console.WriteLine(message1);
- Console.WriteLine(message2);
- return null;
- }
- static void Main(string[] args)
- {
- FunctionPTR = Display;
- FunctionPTR1= Display;
- FunctionPTR("Welcome to function pointer sample.");
- FunctionPTR1("Welcome","This is function pointer sample");
- Console.ReadKey();
- }
- }