Tuesday, October 26, 2004

Delegates in C#, weird.

Here is a link to the article I'm reading about delegates in C#, click here.

Ok so you can make any delegate you want like:
public delegate Boolean DelegateName (parm1, parm2)

The point of the delegate is to make a representive middle man, why? I don't know. So I have a function instead of being called directly, I have it go through a delegate.

As an example given:

public delegate Boolean MyDelegate(Object sendingobj, Int32 x);

public class TestDelegateClass
{
   Boolean MyFunction(Object sendingobj, Int32 x)
   {
      //Perform some processing
      return (true);
   }

   public static void main(String [] args)
   {
      //Instantiate the delegate passing the method to invoke in its constructor
      MyDelegate mdg = new MyDelegate(MyFunction);

      // Construct an instance of this class
      TestDelegateClass tdc = new TestDelegateClass();

      // The following line will call MyFunction
      Boolean f = mdg(this, 1);

   }
}


The tdc is the object and 1 is the int32 value being sent to the delegate function in this case is the myfunction.

That was a single cast delegate, how about a multi-cast delegate?

Multi-cast delegate is basically a linklist of functions to be called instead of one.

The nameing is similar but now instead of boolean it is void, as seen below:
public delegate void DelegateName (parm1, parm2)

so to form two delegates two together a function is called, conviently like this:
public static Delegate Combine(Delegate a, Delegate b);

and to remove a delegate from the linklist, viola:
public static Delegate Remove(Delegate source, Delegate value);

here is the example given:

using System;

class MCD1
{
 public void dispMCD1(string s)
 {
  Console.WriteLine("MCD1");
 }
}

class MCD2
{
 public void dispMCD2(string s)
 {
  Console.WriteLine("MCD2");
 }
}

public delegate void OnMsgArrived(string s);

class TestMultiCastUsingDelegates
{
 public static void Main(string [] args)
 {
  MCD1 mcd1=new MCD1();
  MCD2 mcd2=new MCD2();
  // Create a delegate to point to dispMCD1 of mcd1 object
  OnMsgArrived oma=new OnMsgArrived(mcd1.dispMCD1);

  // Create a delegate to point to dispMCD2 of mcd2 object
  OnMsgArrived omb=new OnMsgArrived(mcd2.dispMCD2);

  OnMsgArrived omc;
  // Combine the two created delegates. Now omc would point to the head of a linked list
  // of delegates
  omc=(OnMsgArrived)Delegate.Combine(oma,omb);

  Delegate [] omd;
  // Obtain the array of delegate references by invoking GetInvocationList()
  omd=omc.GetInvocationList();

  OnMsgArrived ome;
  // Now navigate through the array and call each delegate which in turn would call each of the
  // methods
  for(int i=0;i<omd.Length;i++)
  {
   // Now call each of the delegates
   ome=(OnMsgArrived)omd[i];
   ome("string");
  }
 }
}


No comments: