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:

  1. public delegate TResult Func<[in T,…], out TResult>(
  2. T arg
  3. )
We can pass any number of parameters in Function pointer. It is optional, but we should have the non-void return type.

Example:
  1. class Program
  2. {
  3. static Func<string,string> FunctionPTR = null;
  4. static Func<string,string, string> FunctionPTR1 = null;
  5. static string Display(string message)
  6. {
  7. Console.WriteLine(message);
  8. return null;
  9. }
  10. static string Display(string message1,string message2)
  11. {
  12. Console.WriteLine(message1);
  13. Console.WriteLine(message2);
  14. return null;
  15. }
  16. static void Main(string[] args)
  17. {
  18. FunctionPTR = Display;
  19. FunctionPTR1= Display;
  20. FunctionPTR("Welcome to function pointer sample.");
  21. FunctionPTR1("Welcome","This is function pointer sample");
  22. Console.ReadKey();
  23. }
  24. }