title: Create object instance of correct subtype from raw bytes
body: <p>I have a binary file format I cannot change, and in C# I need to deserialize class instances from it again.</p>
  
  <p>The file contains several byte blocks which represent object instances of a base class. However, one byte in the block specifies which subclass the object once was.</p>
  
  <p>For example, a byte block looks like the following:</p>
  
  <ul>
  <li>General settings which the base class has (let's say <code>Collectible</code>)</li>
  <li>A byte determining what kind of additional details follow (either <code>Coin</code> or <code>ItemBox</code>)</li>
  <li>According to the byte, either details about the <code>Coin</code> (e.g. the coins value) or the <code>ItemBox</code> (e.g. which item it has and how fast it regenerates)</li>
  </ul>
  
  <p>I currently coded a constructor for the <code>Collectible</code> class accepting a BinaryReader to read from. However, after I read the general settings and know which sub type follows, I can't <em>downcast</em> the <code>Collectible</code> class to <code>Coin</code> or <code>ItemBox</code> depending on the type when I'm already in the constructor.</p>
  
  <pre><code>public Collectible(BinaryReader reader)
  {
      // General collectible stuff, position, synced anim...
      X = reader.ReadInt32();
      Y = reader.ReadInt32();
      MusicStartCode = reader.ReadInt32();
      MusicBpm = reader.ReadInt32();
      // ...
  
      // Tricky part: sub-type specific information follows
      CollectibleType type = (CollectibleType)reader.ReadByte();
      switch (type)
      {
          case CollectibleType.Coin:
              // What to do now?
              break;
          case CollectibleType.ItemBox:
              // I ran out of ideas
              break;
      }
  }
  </code></pre>
  
  <p>How do I solve such a problem elegantly and deserialize the binary format back into object instances? I thought of some kind of seeking towards the byte determining the sub type and then create the specific sub class instances. But where would I do that, is there a typical design pattern for this problem?</p>
  
  <p>On a sidenote I think that this format was written by a C++ program originally which just dumped the instances bytes into the file and had no problem casting a byte array pointer back to a class when loading it. But I can't do that in C# or can I (I want to avoid unsafe code)?</p>