I have the following simplistic:

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

You need to do the following:

 ConcretRequest concretRequest = (ConcretRequest)request; 

How to do it?

Update:

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 the class containing the result of the serialization and the type of the serialized object:

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

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

I have a feeling that I reinvent the wheel. But I just can not find how this can be done easier.

  • one
    So you don't know the type at compile time? OK, let's say you could bring the type - and what will you do next? - VladD
  • why not to make RequestPacket a generic and inside to store not a type and a byte, but a field of a particular type and serialize it all together? - Grundy
  • @Grundy, thanks for the comment. But I still can not create an instance of RequestPacket <T> on the server without knowing T. Could you give me an example of use. - Maxim Ryazanov
  • No, could not :) add more details to the question - Grundy
  • Then I just do not understand what you are offering. Suppose I use a generic. On the server, I need to deserialize RequestPacket <T> from byte []. But the server does not know the type T, and the processing of objects of type T occurs in various ways depending on T. For example, a request to check for updates: the login and password are transmitted, the server checks for a pair in the database and returns updates. Nickname change request: a login, a password, a new nickname are transmitted, the server checks for a login and password in the database, changes the nickname, sends confirmation to the client. - Maxim Ryazanov

2 answers 2

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

For example, let it be LoginRequest .

 Request request = (Request)binaryFormatter.Deserialize(memoryStream); if (type == typeof(LoginRequest)) { LoginRequest loginRequest = (LoginRequest)request; // ... дальнейшая работа с loginRequest ... } 

    Try it like this.

     ConcretRequest concretRequest = request as ConcretRequest; if(concretRequest != null) { //TODO: } 

    Beautiful and simple.

    • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky