title: Generic packet system for Lidgren
body: <p>I'm using Lidgren.Networking to send data between server and clients in a client/server architecture. I have created a Packet class to use when sending packets over the network.</p>
  
  <p>Packet.cs</p>
  
  <pre><code>public abstract class Packet : IPackable
  {
      public abstract void PackIntoNetMessage(NetOutgoingMessage msg);
      public abstract void PopulateFromNetMessage(NetIncomingMessage msg);
  }
  </code></pre>
  
  <p>IPackable.cs</p>
  
  <pre><code>interface IPackable
  {
      void PackIntoNetMessage(NetOutgoingMessage msg);
      void PopulateFromNetMessage(NetIncomingMessage msg);
  }
  </code></pre>
  
  <p>Then I have application specific packet classes like this</p>
  
  <pre><code>public class PositionPacket : Packet
  {
      public int PosX { get; set; }
      public int PosY { get; set; }
  
      public override void PackIntoNetMessage(NetOutgoingMessage m)
      {
          m.Write((byte)Networking.PacketTypes.PositionPacket);
          m.Write(PosX);
          m.Write(PosY);
      }
  
      public override void PopulateFromNetMessage(NetIncomingMessage m)
      {
          PosX = m.ReadInt32();
          PosY = m.ReadInt32();
      }
  }
  </code></pre>
  
  <p>Sending the packets is easy, I just create a packet and PackIntoNetMessage(msg) and then send it. But it's when I try to recieve packets I get some annoying structural problems.</p>
  
  <p>I start by reading the first byte</p>
  
  <pre><code>var packetType = (Networking.PacketTypes)incomingMsg.ReadByte();
  </code></pre>
  
  <p>but then I have to make a switch with a case for each packet type in order the get the correct constructor.</p>
  
  <pre><code>switch (packetType)
  {
      case Networking.PacketTypes.PositionPacket:
          incPacket = new Packets.PositionPacket();
          break;
      default:
          incPacket = null;
          break;
  }
  //Populate packet from net message
  incPacket.PopulateFromNetMessage(incomingMsg);
  </code></pre>
  
  <p>This is the part that I don't like. I want to be able to make a generic packet handling system that handles any class deriving from Packet. I guess reflection wont be a good idea since it will kill the performance. How shall I structure this to make it more generic?</p>