0

I have a server and client, I'm serializing packet objects using XmlSerializer and since the type is unknown on the other end, I created the following method to handle that.

Both assemblies contain same types of packets, so only known types will be sent.

public static class Serializer
{
    private static readonly List<Type> packetTypes;

    static Serializer()
    {
        packetTypes = new List<Type>()
        {
            typeof(Packets.ClientPackets.PlayerInformation),
            typeof(Packets.ClientPackets.DoSomething)
        };
    }

    public static IPacket Deserialize(byte[] buffer)
    {
        foreach (var t in packetTypes)
        {
            using (var ms = new MemoryStream())
            {
                try
                {
                    ms.Write(buffer, 0, buffer.Length);
                    ms.Seek(0, SeekOrigin.Begin);

                    var serializer = new XmlSerializer(t);
                    var tempObject = serializer.Deserialize(ms);


                    return (IPacket)tempObject;
                }
                catch (Exception)
                {
                }
            }
        }

        return null;
    }
}

So it loops through all known types figuring it out.

Now this works just fine, but I'm wondering whether there's a more efficient or lets say proper way of doing this? Are there any risks here?

P.S. I'm limited to not being able to use any external libs.

J. Doe
  • 905
  • 1
  • 10
  • 23
  • You could use `XmlSerializerExtensions.DeserializePolymorphicXml(this TextReader textReader, params Type[] types)` from [How to deserialize XML if the return type could be an Error or Success object](https://stackoverflow.com/a/44248192/3744182). It calls [`XmlSerializer.CanDeserialize(XmlReader)`](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.candeserialize.aspx) for each possible type. – dbc Oct 19 '17 at 16:28
  • [These](https://stackoverflow.com/questions/4143421/fastest-way-to-serialize-and-deserialize-net-objects)(https://stackoverflow.com/questions/549128/fast-and-compact-object-serialization-in-net) are some related answers you could find them useful – abiratsis Oct 19 '17 at 16:44

0 Answers0