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.