Skip to content

*.dannyg

an extension of dannyg

Menu
  • Home
  • art
  • inspiration
  • music
  • poetry
  • Recipes
  • writings
Menu

Mission: delegates

Posted on September 4, 2010

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: c#,.net

Leave a Reply

You must be logged in to post a comment.

Recent Posts

  • Reading Room
  • Inspirational Movies / TV shows
  • Remove passphrase from PEM file
  • Parallels Multihoming a CentOS Server
  • Forced Failures

Archives

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org
©2026 *.dannyg | Design: Newspaperly WordPress Theme