Mikalee
Mikalee

Reputation: 289

How set property name/value dynamically?

Hi I'm not sure if I'm describing it properly, but based on a list of strings, I want to set the values of properties that belong to an object (all properties, which are objects, that match the string names):

var _parentObject = _parentObjectService.GetParentObject(viewModel.Id);
var _listOfPropertyNames = GetPropertyNames();

foreach (var item in _listOfPropertyNames)
{
// Pseudo code, I know it's gibberish:
_parentObject.Tests.[item] = viewModel.Tests.[item];

}

Hopefully that makes sense, please let me know if not.

Thank you.

Upvotes: 1

Views: 2526

Answers (2)

SLaks
SLaks

Reputation: 887215

It sounds like you're looking for AutoMapper, which will do all this for you:

//Once:
Mapper.CreateMap<FromType, ToType>();

//Then:
Mapper.Map(viewModel.Tests, _parentObject.Tests);

If you want to do it yourself, you'll need reflection (slow) or compiled expression trees (fast).

Upvotes: 3

Polynomial
Polynomial

Reputation: 28316

Use reflection to set the property value, as per: Set object property using reflection

Really simple example:

void SetParamByName(object obj, string paramName, object value)
{
    obj.GetType()
        .InvokeMember(
            paramName,
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
            Type.DefaultBinder,
            obj,
            value
        );
}

Upvotes: 0

Related Questions