I am currently using Generics to create dynamic methods, such as creating an object and filling properties with values.
Is there a way to "dynamically" create a Generic without knowing the type? For instance:
List<String> = new List<String>()
is a predefined way but
List<(object.GetType())> = new List<(object.GetType()>()
doesn't work ... But can it?
This does not work (Is there a similar approach that works?)
public T CreateObject<T>(Hashtable values) { // If it has parameterless constructor (I check this beforehand) T obj = (T)Activator.CreateInstance(typeof(T)); foreach (System.Reflection.PropertyInfo p in typeof(T).GetProperties()) { // Specifically this doesn't work var propertyValue = (p.PropertyType)values[p.Name]; // Should work if T2 is generic // var propertyValue = (T2)values[p.Name]; obj.GetType().GetProperty(p.Name).SetValue(obj, propertyValue, null); } }
So, in short: how to take the “Type” and create an object from it without using Generics? I used only Generics methods in the methods, but can the same variables be used? I have to define Generic (T) before the method, so can I do the same on the variables before they are "created"?
... or how to use the Activator to create an object using properties instead of parameters. How are you here:
// With parameter values
Test t = new Test("Argument1", Argument2);
// With properties
Test t = new Test { Argument1 = "Hello", Argument2 = 123 };
source share