Dynamically Creating Custom Generic<T> Class and Custom Class at runtime

Dynamically Creating Custom Generic<T> class at runtime:

Step 1: Creating a generic Type

Type d1 = typeof(GenericTupleOfTwo<,>);

Step 2: Creating generic param Type for generic class

Type[] typeArgs = { typeof(string), typeof(List<string>) };

Step 3: Combining the args to the generic type

Type makeme = d1.MakeGenericType(typeArgs);

Step 4: Creating instance of generic class

object
o = Activator.CreateInstance(makeme);

Step 5: Typecasting to form the Generic class

GenericTupleOfTwo<string, List<string>> itsMe = o as GenericTupleOfTwo<string, List<string>>;

Step 6: Setting value for its param

itsMe.First = "First";
itsMe.Second = new List<string>();

Step 7: Code Snippet:

/// <summary>
///
This is used to create instance generic list obj dynamically.
/// </summary>
public void CreateCustomGenericInstance()
{
   //Creating a generic Type.
   Type d1 = typeof(GenericTupleOfTwo<,>);
 
   //Creating generic param Type for generic class.
   Type[] typeArgs = { typeof(string), typeof(List<string>) };
 
   //Combining the args to the generic type.
   Type makeme = d1.MakeGenericType(typeArgs);
                 
   //Creating instance of generic class
   object o = Activator.CreateInstance(makeme);
 
   //Typecasting to form the Generic class.
   GenericTupleOfTwo<string, List<string>> itsMe = o as  
   GenericTupleOfTwo<string, List<string>>;

   //Setting value for its param.
   itsMe.First = "First";
   itsMe.Second = new List<string>();
}

Dynamically Creating Custom Generic<T> class at runtime:

Step 1: Set Namespace.ClassName as target Type

string targetType = "SampleApplication.DynamicClass";

Step 2: Getting the Type of class

Type reflectedType = Type.GetType(targetType);

Step 3: Creating param variables

List<string> list = new List<string>();
list.Add("L");

Step 4: Creating instance for custom class

object obj = Activator.CreateInstance<DynamicClass>();

Step 5: Passing params and invoking the method show from dynamic class

string returnKey = (string)reflectedType.GetMethod("Show").Invoke(obj, new object[] { "arun", 1, true, list });

Step 6: Code Snippet:

public void CustomClass()
{
   //Set Namespace.ClassName as target Type.
   string targetType = "SampleApplication.DynamicClass";
 
   //Getting the Type of class.
   Type reflectedType = Type.GetType(targetType);
 
   //Creating param variables
   List<string> list = new List<string>();
   list.Add("L");
 
   //Creating instance for custom class
   object obj = Activator.CreateInstance<DynamicClass>();
 
   //Passing params and invoking the method show from dynamic class.
   string returnKey = (string)reflectedType.GetMethod("Show")
   .Invoke(obj, new object[] { "arun", 1, true, list });
}

Ebook Download
View all
Learn
View all