title: Dynamically extending a type at runtime?
body: <p>I have the need to extend instances of various types at runtime. Most of the time, I need to work with instances of the original type, however in a few circumstances, I need to create kind of an extension-wrapper around those types that add a couple pieces of contextual information. Something along the lines of the following (which is not actually valid .NET/C# code...but it illustrates the point):</p>
  
  <pre><code>public abstract class BaseClass
  {
    // ...
  }
  
  public class Concrete1: BaseClass
  {
    // ...
  }
  
  public class Concrete2: BaseClass
  {
    // ...
  }
  
  public class WrapperExtender&lt;T&gt;: T // Extending from T here is actually invalid!
    where T: BaseClass
  {
      public WrapperExtender(T extensionTarget)
      {
          m_extensionTarget = extensionTarget;
      }
  
      private readonly T m_extensionTarget;
  
      public object ContextualReference { get; }
      public int ContextualValue { get; }
  
      // DERP: Would need to implement overrides of T here...buuut...can't...
  }
  
  // In use, special case:
  var instance = new Concrete1();
  var extendedInstance = new WrapperExtender(instance);
  
  var processor = new SomeProcessorRequiringExtendedInstance();
  processor.DoProcessing(extendedInstance);
  </code></pre>
  
  <p>Another example of this would probably be Microsoft Entity Framework v4.0, or nHibernate. Both of these frameworks provide dynamically extended instances of your entity types, wrapping them internally to provide, at runtime, the hooks required to keep a data/object/session context up to date with changes made to your entity instances. My needs are not nearly as complex, and the generics scenario above would work beautifully, if only there was a way to blend generics and dynamic typing somehow. </p>
  
  <p>Anyway, I'm hoping someone knows how to achieve the above scenario. Or, perhaps even better, someone knows a better solution. I don't care much for the idea of dynamically extending a type like that at runtime (it doesn't make as much sense as it does in the EF/nHibernate scenario.) At the moment, its the only thing I can really think of that will provide me with the information I need in the processor for each type passed in to DoProcessing.</p>