Mission: delegates

Wanted to do a refresher on delegates before learning more about LINQ

 

delegate void Callback();
 
void Main()
{
    MakeRequest(AfterRequest2);
}
 
private void MakeRequest(Callback callback)
{
    "Request Made".Dump();
    callback();
}
 
private void AfterRequest()
{
    "Stuff done after request".Dump();    
}
 
private void AfterRequest2()
{
    "Different stuff done after request".Dump();    
}

 

Here is another sample I played with. This one uses anonymous delegates and outer variables.

  delegate bool GreaterThanHandler (int first, int second);
 
  void BubbleSort(int[] items, GreaterThanHandler greaterThan)
  {
        int i;
      int j;
      int temp;
 
      for (i = items.Length - 1; i >= 0; i--)
      {
          for (j = 1; j <= i; j++)
          {
              if (greaterThan(items[j - 1], items[j]))
              {
                  temp = items[j - 1];
                  items[j - 1] = items[j];
                  items[j] = temp;
              }
           }
        }
 
  }
  
  bool GreaterThan(int first, int second)                     
  {
      return (first > second);
  }
  
  bool LessThan(int first, int second)
  {
        return (first < second);  
  }
 
  void Main()
  {  
      int i;
      int[] items = new int[] { 1,2,3,4,5 };
      int swapCount = 0;
      
      BubbleSort(items, delegate(int first, int second) 
      {
           bool swap = (first > second % 2);
         if (swap) swapCount++;
         return swap;      
      });                           
 
      for (i = 0; i < items.Length; i++)
      {
          items[i].Dump();          
      }
      
      
      "Number of swaps: ".Dump();
      swapCount.Dump();
  }
 
Technorati Tags: ,

Leave a Reply