title: Instantiate an object with a runtime-determined type
body: <p>I'm in a situation where I'd like to instantiate an object of a type that will be determined at runtime.  I also need to perform an explicit cast to that type.</p>
  
  <p>Something like this:</p>
  
  <pre><code>static void castTest(myEnum val)
  {
      //Call a native function that returns a pointer to a structure
      IntPtr = someNativeFunction(..params..);
  
      //determine the type of the structure based on the enum value
      Type structType = getTypeFromEnum(val);
  
      structType myStruct = (structType)Marshal.PtrToStructure(IntPtr, structType);
  }
  </code></pre>
  
  <p>This is obviously not valid code, but I hope it conveys the essence of what I'm trying to do.  The method I'm actually working on will have to perform the marshaling operation on ~35 different types.  I have several other methods that will need to do something similar with the same set of types.  So, I'd like to isolate the type-determining logic from these methods so that I only need to write it once, and so that the methods stay clean and readable.</p>
  
  <p>I must admit to being a total novice at design. Could anyone suggest a good approach to this problem?  I suspect there might be an appropriate design pattern that I'm unaware of.</p>