1

I want to cast an object with the type known at runtime.

For example:

string className= "Model.Menu"; // which is a class in the solution
var bytesAsString = Encoding.UTF8.GetString(requestModel.data);
var decompress = CompressionUtils.Decompress(requestModel.data);
var bf = new BinaryFormatter();
var mappedCollection = (**Menu**)bf.Deserialize(new MemoryStream(decompress)); // here I want to use the above className for casting. 
Ignasi93
  • 533
  • 2
  • 5
  • 14
  • 3
    It´s not possible to cast that way, because casting is a **compile-time-thing**. The compiler has no knowledge of your type passed at **runtime**. What do you want to do with `mappedCollection` afterwards? Can you use a base-interface all your classes implement and cast to that instead? – MakePeaceGreatAgain Jan 09 '20 at 09:03
  • The type of a variable must be defined at compile-time (yes, even if you use `var`). What type do you expect `mappedCollection` to be? – John Wu Jan 09 '20 at 09:14
  • it should be "Model.Menu" – Vidhyut Kediya Jan 09 '20 at 09:16

0 Answers0