Alex Rivera | Logout

What is the difference between delegate in c# and function pointer in c++?

Asked 2011-11-11T16:49:14.850
28

Possible Duplicate:
are there function pointers in c#?

I'm interested in finding the difference between delegate in C# and function pointer in C++.

Edit
Report

1 Answer

38

A delegate in C# is a type-safe function pointer with a built in iterator.

It's guaranteed to point to a valid function with the specified signature (unlike C where pointers can be cast to point to who knows what). It also supports the concept of iterating through multiple bound functions.

In C#, delegates are multi-cast meaning they can iterate through multiple functions. For example:

class Program
{
   delegate void Foo();

   static void Main(string[] args)
   {
      Foo myDelegate = One;
      myDelegate += Two;

      myDelegate(); // Will call One then Two
   }

   static void One()
   {
      Console.WriteLine("In one..");
   }

   static void Two()
   {
      Console.WriteLine("In two..");
   }
}
answered 2011-11-11T16:53:25.543

Your Answer