c# – How to cast an object of a base type to a derived one, knowing the Type?


Simplified I have the following:

Type type; //тип класса, производного от Request (в данном случае ConcretRequest)
Request request;

You need to do the following:

ConcretRequest concretRequest = (ConcretRequest)request;

How to do it?


I need it to transfer data to the server. Objects of classes derived from Request are containers for data. On the client side, I serialize them and create an object of a class containing the result of the serialization and the type of the serialized object:

public class RequestPacket
    public Type type;
    public byte[] requestBytes;

I serialize the RequestPacket and send it to the server. On the server, I deserialize in a RequestPacket . Next, I need to deserialize requestBytes into an instance of a class derived from Request .

I have a feeling that I am reinventing the wheel. But I can't find any way to make it easier.


In your byte array (and then in the Request request field) there is a ready-made object of the right type right away, which must be converted to a specific type somewhere further during processing.

For example, let it be LoginRequest .

Request request = (Request)binaryFormatter.Deserialize(memoryStream);

if (type == typeof(LoginRequest))
    LoginRequest loginRequest = (LoginRequest)request;
    // ... дальнейшая работа с loginRequest ...
Scroll to Top