title: Event Handlers and Interfaces
body: <p>I have an interface called IDataIO:</p>
  
  <pre><code>public interface IDataIO
  {
    event DataReceivedEvent DataReceived;
    //.....more events,methods and properties
  }
  </code></pre>
  
  <p>I also have multiple classes that implement this interface, namely <code>UdpIO</code>, <code>TcpIO</code>, <code>SerialIO</code>.</p>
  
  <p>Now, I have an <code>IO</code> class that allows me to switch between different input/output hardware. Each instance of this class has a <code>CurrentIODevice</code> property, which could be one of <code>SerialIO</code>,<code>UdpIO</code> or <code>TcpIO</code>. When this property is assigned, i attach 1 or more handlers to the <code>DataReceivedEvent</code> so that my GUI is notified when incoming data is received, as well as other classes that need to be notified.</p>
  
  <pre><code>public class IO
  {
    IDataIO CurrentIODevice;
  
    public IO()
    {
      SerialIO serial = new SerialIO();
      TcpIO tcp = new TcpIO();
      UdpIO udp = new UdpIO();
      CurrentIODevice = serial;
    }
  }
  </code></pre>
  
  <p>I also have a <code>IOManager</code> class that holds multiple <code>IO</code> objects. </p>
  
  <pre><code>public class IOManager
  {
    List&lt;IO&gt; Ports = new List&lt;IO&gt;();
    public IOManager()
    {
      Ports.Add(new IO());
      Ports.Add(new IO());
    }
  
    Ports[0].CurrentIODevice = serial;
    Ports[0].CurrentIODevice.DataReceivedHandler += MyGuiUpdate;
    Ports[0].CurrentIODevice.DataReceivedHandler += MyDataProcessing;
  }
  </code></pre>
  
  <p>My concern (its not an issue atm) is how I am going to change between different IDataIO interfaces at runtime.</p>
  
  <p>What is the effect of, at runtime, performing the following statement:</p>
  
  <pre><code>//i know this is illegal but just to demonstrate
  IOManager.Ports[0].CurrentIODevice = tcp; 
  </code></pre>
  
  <p>Will the event handlers still be functioning (and correctly)? </p>
  
  <p>Do i need to unassign the events before the CurrentIODevice is assigned, and then re-assign the handlers again after? If this is the case, I can see this approach getting quite messy, so if anyone has a better approach to this problem I'm all ears :)</p>