title: Dynamically creating a proxy class
body: <p>I am trying to create a proxy class dynamically.  I know there are some very good frameworks out there to do this but this is purely a pet project as a learning exercise so would like to do it myself.</p>
  
  <p>If, for example, I have the following class implementing an interface:</p>
  
  <pre><code>interface IMyInterface
  {
      void MyProcedure();
  }
  
  class MyClass : IMyInterface
  {
      void MyProcedure()
      {
          Console.WriteLine("Hello World");
      }
  }
  </code></pre>
  
  <p>To intercept methods to this class in order to log them, I am creating another class (my version of a proxy class) which implements the same interface but contains a reference to the 'real' class.  This class performs an action (e.g. logging) and then calls the same method on the real class.</p>
  
  <p>For example:</p>
  
  <pre><code>class ProxyClass : IMyInterface
  {
      private IMyInterface RealClass { get; set; }
  
      void MyProcedure()
      {
          // Log the call
          Console.WriteLine("Logging..");
  
          // Call the 'real' method
          RealClass.MyProcedure();
      }
  }
  </code></pre>
  
  <p>The caller then calls all methods on the proxy class instead (I am using a basic home-brew IoC container to inject the proxy class in place of the real class).  I am using this method because I would like to be able to swap out <code>RealClass</code> at run time to another class implementing the same interface.</p>
  
  <p>Is there a way to create <code>ProxyClass</code> at run time and populate its <code>RealClass</code> property so it can be used as a proxy for the real class?  Is there a simple way to do this or do I need to use something like <code>Reflection.Emit</code> and generate the MSIL?</p>