string to variable name
Solution 1:
You can use reflection to set the properties 'by name'.
using System.Reflection;
...
myCustomer.GetType().GetProperty(item.Key).SetValue(myCustomer, item.Value, null);
You can also read the properties with GetValue, or get a list of all property names using GetType().GetProperties(), which returns an array of PropertyInfo (the Name property contains the properties name)
Solution 2:
Well, you can use Type.GetProperty(name)
to get a PropertyInfo
, then call GetValue
.
For example:
// There may already be a field for this somewhere in the framework...
private static readonly object[] EmptyArray = new object[0];
...
PropertyInfo prop = typeof(Customer).GetProperty(item.key);
if (prop == null)
{
// Eek! Throw an exception or whatever...
// You might also want to check the property type
// and that it's readable
}
string value = (string) prop.GetValue(customer, EmptyArray);
template.SetTemplateAttribute(item.key, value);
Note that if you do this a lot you may want to convert the properties into Func<Customer, string>
delegate instances - that will be much faster, but more complicated. See my blog post about creating delegates via reflection for more information.
Solution 3:
Reflection is an option, but 200 properties is... a lot. As it happens, I'm working on something like this at the moment, but the classes are created by code-gen. To fit "by name" usage, I've added an indexer (during the code generation phase):
public object this[string propertyName] {
get {
switch(propertyName) {
/* these are dynamic based on the the feed */
case "Name": return Name;
case "DateOfBirth": return DateOfBirth;
... etc ...
/* fixed default */
default: throw new ArgumentException("propertyName");
}
}
}
This gives the convenience of "by name", but good performance.
Solution 4:
Use reflection and a dictionary object as your items collection.
Dictionary<string,string> customerProps = new Dictionary<string,string>();
Customer myCustomer = new Customer(); //Or however you're getting a customer object
foreach (PropertyInfo p in typeof(Customer).GetProperties())
{
customerProps.Add(p.Name, p.GetValue(customer, null));
}