0

This question will seem similar to some that have been asked before, but bear with me.

Basically, I want to instantiate a variable at runtime using nothing but a string that represents the type the variable needs to be. Pretty much every existing question gave me something like this:

Type type = Type.GetType(stringrepresentingType);
var newObject = Activator.CreateInstance(type);

This works, but as it stands, newObject is type object. I want to be able to convert the object created by the Activator into the type stored in type, so it would look like this:

Type type = Type.GetType(stringRepresentingType);
var newObject = (type)Activator.CreateInstance(type);

This throws errors due to type being a variable. I've also tried typeof(type) and (Type.GetType(stringRepresentingType) before the Activator, and neither work.

How can I convert the newObject variable without using an if/else?

Edit: I'll be using newObject in logical comparisons (such as == or ||), hence the reason I can't leave it as type object. I know I can just use an if/else to check the type after the fact, but I was curious if there was a more elegant solution. I'd use dynamic as opposed to var, but unfortunately Unity3D does not support it.

GReusch
  • 51
  • 1
  • 4
  • Generics are your friend. – Rob Jan 30 '17 at 06:11
  • 1
    @Rob, Generics will not help here -because type known only in runtime. – Fabio Jan 30 '17 at 06:16
  • @Fabio Good catch, I missed the string being used to create the type. – Rob Jan 30 '17 at 06:17
  • @GReusch Since you don't know the type at compile time, there's no use in casting it to anything except object. Any intellisense/type checking provided will be useless - since it could be *anything* at runtime. – Rob Jan 30 '17 at 06:17
  • 1
    `newObject` is already the instance of type you want. Can you show how you use it and why you need to cast it? – Fabio Jan 30 '17 at 06:18
  • Maybe go with dynamic keyword, because this is made for something like this. But not sure if this bring you any advantage in your case. – Sebi Jan 30 '17 at 06:19
  • GReusch, Please read [var vs. dynamic](http://stackoverflow.com/questions/961581/whats-the-difference-between-dynamicc-4-and-var) carefully. If that post does not help - make sure to [edit] your question with explanation how you plan to use your `newObject` strongly typed value. – Alexei Levenkov Jan 30 '17 at 06:31
  • Try checking `if(newObject is YourType)` which should return true I believe, you would have to manually cast it to let compiler know on compile time – Ali Baig Jan 30 '17 at 06:31

0 Answers0