0

I am updating a loooong... list of properties of an object. I was wondering if there was a way to pass the propertyName as a parameter.

So that, after I checked that the property exists in the object (that I know how to do) - I could just write UpdateObject(ObjectName, propertyName, NewValue).

As you can tell, I'm at the bottom of the learning curve in C#. I have already looked up "similar questions" regarding this issue in SO, without success, at least that I could understand...

If you could point me in the right direction, that would be very kind.

Anyhow, I'll have to thank this fine community of SO'contributors, because over the years I've gotten many, many hints and answers from your posts.

Actually, I followed your advice and went with :

Type type = target.GetType();
PropertyInfo prop = type.GetProperty("propertyName");
prop.SetValue (target, propertyValue, null);
// where target is the object that will have its property set.

Thanks to all

  • *If you could point me in the right direction* `System.Reflection` get object type, find given property, set it – Selvin Aug 01 '19 at 09:58
  • 2
    Do you mean replacing 'obj.X = Y' with 'UpdateObject(obj, 'X', Y)' ? – felix-b Aug 01 '19 at 10:00
  • Look at this answer about how to do this with `System.Reflection` https://stackoverflow.com/a/619778/8882410 – Lemm Aug 01 '19 at 10:00
  • Sounds like you want to use something like AutoMapper. – Kieran Devlin Aug 01 '19 at 10:46
  • 1
    There are ways to do this. But because you say you're learning C#, it's probably better to ask why you want to do it. It's a normal part of the learning process that we want to go against the grain of the way the language works, and that leads to using reflection. But if we understand why you're trying to do that - what problem you're trying to solve - then maybe there's a solution that doesn't require that. – Scott Hannen Aug 01 '19 at 15:41

1 Answers1

1

You can do that using reflection something like this:

class Prop
{
   public string Name {get;set;}
   public object Value {get;set;}
}

public void AssignProperties(object obj, List<Prop> properties)
{
   var objPropSetters = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToDictionary(p => p.Name, p => p.GetSetMethod()); // create a dictionary where the key is the property name and the value is the property's setter method
   properties.ForEach(p => objPropSetters[p.Name].Invoke(obj, p.Value)); // Invoke the setter
}

You can improve performance by caching the objPropSetters per type for reuse.

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99