How do I implement function pointers in C#?
Delegates provide the functionality of function pointers in C#. Here is an example that illustrates both:
Function pointer example:
typedef int (*FUNC_PTR)(void *, void *);
int Compare(void* a, void* b) { ... }
int CallFunction(void* a, void*b)
{
FUNC_PTR myFunc = Compare;
for (i = left+1; i <= right; i++)
if (myFunc(v[i], v[left]) < 0)
}
Equivalent delegate example:
public delegate int FUNC(object x, object y);
public int Compare(object x, object y) { ... }
public void sort()
{
CMP_Func myFuncObj = new FUNC(Compare);
...
if (myFuncObj(x, y) < 0)
System.Console.WriteLine("Object X is less than Object Y");
else if (myFuncObj(x, y) = 0)
System.Console.WriteLine("Object X equals Object Y");
else
System.Console.WriteLine("Object X is greater than Object Y");
}
Index