tags:

views:

134

answers:

2

Hi:

In c or c++ we can use function pointer as a parameter to another function like this:

int example(FUNPTR a)
{
  /* call the function inside */
  a();
}

And I also know that we can use delegates in c# as function pointer, but what if the method I want to assign to the delegate exists in another class, does that mean both class need to have a same delegate declaration?

For example:

class a
{
   public delegate void processData(Byte[] data);

   public void receivData(ProcessData dataHandler)
   {
      NetworkStream stream;
      Byte[] data_buffer = new Byte[100];

      /* receive data from socket interface */

      stream.Read(data_buffer, 0, data_buffer.Length);

      dataHandler(data);
   }
}

and I want to use this receivData function in Class b like this:

class b
{

   public delegate void processData(Byte[] data);

   class a = new a();

   a.receivData(new processData(b.dataHandler));

   public void dataHandler(Byte[] array)
   {
      /* handling of the array*/
   }
}

Please let me know the declaration of processData in class b is necessary.

Is this the right way to do the passing of function pointer in C#?

Thanks

A: 

Yep, the method should have the same signature

mfeingold
Thanks for the reply. Is there a better way of doing this. Having to declare the a same delegates in different classes sounds redundant.
alex
+2  A: 

You do not need multiple declarations of the delegate type, and in fact this will cause problems in your example.

a.receiveData is expecting a delegate of type a.processData. But when you new up a processData delegate in b, that will find the b.processData type -- which is a different type (even though it has the same signature).

So you should remove the delegate type declaration from b, and change your call to:

a.receivData(new a.processData(b.dataHandler));

But in fact the explicit new is unnecessary: since b.dataHandler has the correct signature, the C# compiler will insert an implicit conversion to a.processData, so you can write:

a.receivData(b.dataHandler);
itowlson