A avagarwal Feb 26, 2009 #1 Hi, How can an Instance be created if we have the PropertyInfo for the same. Thanks Anurag
M Marc Gravell Feb 26, 2009 #2 You create an instance of a Type. This could be the prop.PropertyType or the prop.DeclaringType. In the case: class Foo { public Bar SomeProperty {get;set;} } then the PropertyType of SomeProperty is Bar, and the DeclaringType is Foo. Once you have the desired Type, use Activator: object obj = Activator.CreateInstance(type); If you also want to assign the new instance to the property: object obj = prop.PropertyType; // typeof(Bar) prop.SetValue(fooInstance, obj, null); Marc Gravell [C# MVP]
You create an instance of a Type. This could be the prop.PropertyType or the prop.DeclaringType. In the case: class Foo { public Bar SomeProperty {get;set;} } then the PropertyType of SomeProperty is Bar, and the DeclaringType is Foo. Once you have the desired Type, use Activator: object obj = Activator.CreateInstance(type); If you also want to assign the new instance to the property: object obj = prop.PropertyType; // typeof(Bar) prop.SetValue(fooInstance, obj, null); Marc Gravell [C# MVP]
M Marc Gravell Feb 26, 2009 #3 (oops; typo) object obj = Activator.CreateInstance(prop.PropertyType); // typeof (Bar) prop.SetValue(fooInstance, obj, null);
(oops; typo) object obj = Activator.CreateInstance(prop.PropertyType); // typeof (Bar) prop.SetValue(fooInstance, obj, null);