Create Instance from PropertyInfo

A

avagarwal

Hi,

How can an Instance be created if we have the PropertyInfo for the
same.

Thanks

Anurag
 
M

Marc Gravell

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

(oops; typo)

object obj = Activator.CreateInstance(prop.PropertyType); // typeof
(Bar)
prop.SetValue(fooInstance, obj, null);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top