0
internal interface Rule {
}

private class Rule<T> : Rule {
   //Properties & Other Stuff
}

void method() {
   //For simplicity I used string here. It can be anything when the code is in context
   Type _type = typeof(string); 
   Rule[] _rules;

   //This is causing an error because _type could not be found
   _rules = new Rule<_type>[] { }; 
}

Is it even possible to instantiate a class with a generic type that is stored in a variable?

-- EDIT

From my first example I thought I would be able to apply the same concept for calling a method. But it seems that I was wrong. I'm trying to use newtonsoft json library to deserialize a string as a generic type. I found this question that allows you to invoke a method with a generic type. I looked around on how to cast the object to _foo but could only find casting where the type is known. Any idea?

Using Newtonsoft.Json;


void method() {
   //For simplicity I used string here. It can be anything when the code is in context
   Type _type = typeof(string); 
   Rule[] _rules;

   // ------------------ New Additions ----------------
   var _foo = (Rule[])Array.CreateInstance(typeof(Rule<>).MakeGenericType(_type),0);

   MethodInfo method = typeof(JsonConvert).GetMethod("DeserializeObject");
   MethodInfo generic = method.MakeGenericMethod(_foo.GetType());

   //How do you cast this to a type _myType?
   _rules = generic.Invoke(this, new[] { "JSON Data" });
}
Community
  • 1
  • 1
  • This is mostly duplicate of http://stackoverflow.com/questions/1151464/how-to-dynamically-create-generic-c-sharp-object-using-reflection... But not exactly due to twist of http://stackoverflow.com/questions/400900/how-can-i-create-an-instance-of-an-arbitrary-array-type-at-runtime – Alexei Levenkov Nov 22 '14 at 03:03
  • possible duplicate of [Pass An Instantiated System.Type as a Type Parameter for a Generic Class](http://stackoverflow.com/questions/266115/pass-an-instantiated-system-type-as-a-type-parameter-for-a-generic-class) – Ben Aaronson Nov 22 '14 at 03:06

1 Answers1

2

It's possible, but you have to use reflection:

Type genericTypeDefinition = typeof(Rule<>);
Type genericType = genericTypeDefinition.MakeGenericType(_type);
Rule[] array = (Rule[])Array.CreateInstance(genericType, 0);
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758