Removing an Event Handler - CSharp Custom Type

CSharp examples for Custom Type:Event

Description

Removing an Event Handler

Demo Code

using System;/*from w w  w. ja  v  a  2 s.  co m*/
delegate void CharEventHandler(object source, CharEventArgs e);
public class CharEventArgs : EventArgs
{
   public char CurrChar;
   public CharEventArgs(char CurrChar)
   {
      this.CurrChar = CurrChar;
   }
}
class CharChecker
{
   char curr_char;
   public event CharEventHandler TestChar;
   public char currentCharacter
   {
      get { return curr_char; }
      set
      {
         if (TestChar != null )
         {
            CharEventArgs args = new CharEventArgs(value);
            TestChar(this, args);
            curr_char = args.CurrChar;
         }
      }
   }
}
class Events2
{
   public static void Main()
   {
      CharChecker tester = new CharChecker();
      tester.TestChar += new CharEventHandler(Drop_A);
      tester.TestChar += new CharEventHandler(Change_D);
      tester.currentCharacter = 'B';
      Console.WriteLine("{0}", tester.currentCharacter);
      tester.currentCharacter = 'r';
      Console.WriteLine("{0}", tester.currentCharacter);
      tester.currentCharacter = 'a';
      Console.WriteLine("{0}", tester.currentCharacter);
      tester.currentCharacter = 'd';
      Console.WriteLine("{0}", tester.currentCharacter);

      Console.WriteLine("\nRemoving event handler....");
      tester.TestChar -= new CharEventHandler(Change_D);

      tester.currentCharacter = 'D';
      Console.WriteLine("{0}", tester.currentCharacter);
      tester.currentCharacter = 'D';
      Console.WriteLine("{0}", tester.currentCharacter);
      tester.currentCharacter = 'd';
      Console.WriteLine("{0}", tester.currentCharacter);
   }
   static void Drop_A(object source, CharEventArgs e)
   {
      if(e.CurrChar == 'a' || e.CurrChar == 'A' )
      {
         Console.WriteLine("Don't like 'a'!");
         e.CurrChar = 'X';
      }
   }
   static void Change_D(object source, CharEventArgs e)
   {
      if(e.CurrChar == 'd' || e.CurrChar == 'D' )
      {
         Console.WriteLine("D's are good!");
         e.CurrChar = 'Z';
      }
   }
}

Result


Related Tutorials