Function Pointer in C#

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,stringstring> FunctionPTR1 = null;  
  5.   
  6.     static string Display(string message)  
  7.     {  
  8.         Console.WriteLine(message);  
  9.         return null;  
  10.     }  
  11.   
  12.     static string Display(string message1,string message2)  
  13.     {  
  14.         Console.WriteLine(message1);  
  15.         Console.WriteLine(message2);  
  16.         return null;  
  17.     }  
  18.     static void Main(string[] args)  
  19.     {  
  20.         FunctionPTR = Display;  
  21.         FunctionPTR1= Display;  
  22.         FunctionPTR("Welcome to function pointer sample.");  
  23.         FunctionPTR1("Welcome","This is function pointer sample");  
  24.         Console.ReadKey();  
  25.     }  
  26. }  

 

Ebook Download
View all
Learn
View all