title: Serialize and Deserialize a packet
body: <p>i m trying to get a bit deeper into sockets applications , and i'm trying to create a server/Client application with <strong>Packets</strong> as a <strong>Serialized Classes</strong> 
  <br>Example : </p>
  
  <pre><code>[Serializable]
  class Msg 
  {
      public String Cmd { get; set; }
  
      public Msg(String M)
      {
          this.Cmd = M;
      }
  
  }
  </code></pre>
  
  <p>I m trying to make it easy to read and <strong>cleaner</strong> using <code>interfaces</code></p>
  
  <pre><code>public interface Packet
  {
      void Execute();
  }
  </code></pre>
  
  <p>Packets : </p>
  
  <pre><code>[Serializable]
  class Msg : Packet
  {
      public String Cmd { get; set; }
  
      public Msg(String M)
      {
          this.Cmd = M;
      }
      public void Execute()
      {
        Sender.Send(this);
      }
  }
  </code></pre>
  
  <p>My question is while Deserializing the Packet is it possible to Deserialize to know the type of the packet for example : </p>
  
  <pre><code>   Packet p = (Packet)Data; // data is the packet sent by the Client Desiralized
     var type = p.GetType();
  </code></pre>
  
  <p>then use it like : </p>
  
  <pre><code>if (type== Typeof(Packet.Msg))
     {
         // handle data
     }
  </code></pre>
  
  <p>is it possible to get packet type across Packet Interface?
  <br/><strong>EDIT :</strong> 
  cause i noticed in .NET in System.Type reference there is  GetType Method Return the Type of the Class so i was a was trying to know if it can returns the type of the class (packet)</p>
  
  <p>Something Like : </p>
  
  <pre><code>    public void Send&lt;T&gt;(T packet) where T : IPacket
      {
          if (!Connected || packet == null) return;
  
          lock (_sendBuffers)
          {
              using (MemoryStream ms = new MemoryStream())
              {
                  try
                  {
                      _parentServer.Serializer.Serialize(ms, packet);
                  }
                  catch (Exception)
                  {
                      Disconnect();
                      return;
                  }
  
                  byte[] payload = ms.ToArray();
  
                  _sendBuffers.Enqueue(payload);
  
                  OnClientWrite(packet, payload.LongLength, payload);
  
                  lock (_sendingPacketsLock)
                  {
                      if (_sendingPackets) return;
  
                      _sendingPackets = true;
                  }
                  ThreadPool.QueueUserWorkItem(Send);
              }
          }
      }
  </code></pre>