jdavis
jdavis

Reputation: 8665

Using reflection to create an object represented by the contents of a "Type" object

I am using reflection to find a type by a string like this...

Type currentType = Type.GetType(typeName);

I then am able to get a list of properties for that type like this...

var props = currentType.GetProperties();

How do I instantiate a new object of this type and then start assigning values to the properties of that object based on the list of properties in the props list?

Upvotes: 2

Views: 1602

Answers (2)

M.Babcock
M.Babcock

Reputation: 18965

Instantiate the currentType with:

var newInst = Activator.CreateInstance(currentType);

and assign property values with:

propInfo.SetValue(newInst, propValue, BindingFlags.SetProperty, null, null, null);

Where propInfo is the PropertyInfo instance from your props and propValue is the object you want to assign to the property.

EDIT:

I always lean towards using the more verbose SetValue overload because I've had problems with the short one in the past, but propInfo.SetValue(newInst, propValue, null); might work as well.

Upvotes: 1

Austin Salonen
Austin Salonen

Reputation: 50245

Using the values you already have...

var created = Activator.CreateInstance(currentType);

foreach(var prop in props)
{
    prop.SetValue(created, YOUR_PROPERTY_VALUE, null);
}

Upvotes: 4

Related Questions