2

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?

2 Answers 2

4

Using the values you already have...

var created = Activator.CreateInstance(currentType);

foreach(var prop in props)
{
    prop.SetValue(created, YOUR_PROPERTY_VALUE, null);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.