Search code examples
c#serializationdeserializationtcpclienttcp

How to know the type of deserialized class??(or objects)


I have two classes

[Serializable]    
public class Class1
{                
    public List<String[]> items= new List<string[]>();        
}

[Serializable]
public class Class2
{
    public List<String[]> items = new List<string[]>();                
}

and I serialize these classes and send data to clients like this

NetworkStream stream = client.GetStream();
MemoryStream memory = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();

Class1 data = new Class1(); // or Class2
data.items.Add(new String[]{"1", "2", "3"});       

bf.Serialize(memory, data);
memory.Position = 0;

byte[] buffer = memory.ToArray();                        

stream.Write(buffer, 0, buffer.Length);
stream.Flush();

When Client program receive data from server, the program handle the data like this

BinaryFormatter bf = new BinaryFormatter();
MemoryStream memory = new MemoryStream();
NetworkStream stream = client.GetStream();

int bufferSize = client.ReceiveBufferSize;
byte[] buffer = new byte[bufferSize];
int bytes = stream.Read(buffer, 0, buffer.Length);

memory.Write(buffer, 0, buffer.Length);
memory.Position = 0;

BUT in this situation, I don't know what is the type of data...Is Class1??? or Class2..

How to know the type of deserialized class??(or objects)


Solution

  • You should be able to deserialize it as an object, then use GetType()

    GetType(new BinaryFormatter().Deserialize(stream));