Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a property into a method to change that property

Not sure if this is possible, but here is what I am trying to do:

I want to have a dictionary that contains a mapping of a column index to a property name used to populate that index.

In my code I will loop through an array if strings and use the dictionary to look up which column it should map to.

My end result code would look like:

for(int index = 0; index < fields.Length)
{
    fieldPropertyMapping[index] = StripQuotes(fields[index]);
}
like image 473
John Sonmez Avatar asked Jun 25 '10 18:06

John Sonmez


2 Answers

To do what you're asking specifically, you'll have to use reflection (as you tagged your question) to do this. Have a look at the PropertyInfo class. I'm not entirely certain what your code is doing, but a general example of reflectively setting a property value would be:

object targetInstance = ...; // your target instance

PropertyInfo prop = targetInstance.GetType().GetProperty(propertyName);

prop.SetValue(targetInstance, null, newValue);

You could, however, pass an Action<T> instead, if you know the property at some point in the code. For example:

YourType targetInstance = ...;

Action<PropertyType> prop = value => targetInstance.PropertyName = value;

... // in your consuming code

prop(newValue);

Or, if you know the type when you call it but you don't have the instance, you could make it an Action<YourType, PropertyType>. This also would prevent creating a closure.

Action<YourType, PropertyType> prop = (instance, value) => instance.PropertyName = value;

... // in your consuming code

prop(instance, newValue);

To make this fully generic ("generic" as in "non-specific", not as in generics), you'll probably have to make it an Action<object> and cast it to the proper property type within the lambda, but this should work either way.

like image 186
Adam Robinson Avatar answered Nov 14 '22 22:11

Adam Robinson


You have a couple of choices:

  1. Use reflection. Store and pass a PropertyInfo object into the method and set it's value through reflection.
  2. Create an ActionDelegate with a closure to that property and pass that into the method.
like image 25
LBushkin Avatar answered Nov 14 '22 21:11

LBushkin