I got the following code to create my class :
public class GenericObject<T>
{
[...]
public GenericObject(object source, string propertyName)
{
[...]
}
}
and then I’d like to create instances of my Class. here is the loop I have :
foreach (PropertyInfo pi in container.GetType().GetProperties())
{
//var type = pi.PropertyType;
GenericObject<pi.PropertyType> p = new GenericObject<pi.PropertyType>(container, pi.Name);
}
The compiler tells me that ‘pi’ is not a namespace (???)
I tried with this code :
Type type = pi.PropertyType;
GenericObject<type> p = new GenericObject<type>(container, pi.Name);
but I got the same error (‘type’ not a namespace)
What have I to do ? thx in advance for any help
The problem you have is that
pi.PropertyTypeis a variable that contains a class that represents a type, not a type its self.Generics expect a type, not a variable. You could dynamically create the type as per Jakub’s answer, although i’m not sure that’s what you want or need.
To be honest i’m not sure how much better your generic class is than just having one that holds
objects. Since you’re going to be creating this generic class with reflection, you’re not going to get the type-safety you’d typically use generics for.