user2881275
user2881275

Reputation: 33

Initialize a generic class with the generic type as a variable

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" });
}

Upvotes: 0

Views: 790

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292425

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);

Upvotes: 2

Related Questions