Use delegates to do callback - CSharp Custom Type

CSharp examples for Custom Type:delegate

Description

Use delegates to do callback

Demo Code

using System;/*from  w w w . j a  va  2 s . c om*/
public struct Person {
   public string FName;
   public string LName;
}
public delegate void OnNewHire( Person person );
public class HR {
   public void OnNewHire( Person person ) {
      Console.WriteLine("HR is in the process of putting {0} to sleep", person.FName );
   }
}
public class Department {
   private OnNewHire   m_OnNewHireDelegate = null;
   public void AddOnNewHireDelegate( OnNewHire onh ) {
      m_OnNewHireDelegate = onh;
   }
   public void HirePerson( Person p ) {
      if( m_OnNewHireDelegate != null )
         m_OnNewHireDelegate( p );
      }
   }
   public class DelegateTest {
      public static void Main( ) {
         HR hr = new HR( );
         Department dept = new Department( );
         //Register the OnNewHire Delegate
         dept.AddOnNewHireDelegate( new OnNewHire( hr.OnNewHire ) );
         Person me;
         me.FName = "D";
         me.LName = "W";
         dept.HirePerson( me );
      }
}

Result


Related Tutorials