Possible Duplicate:
How can I code a C# function to accept a variable number of parameters?
I have the following class:
public class Product : AuditableTable
{
public string Position { get; set; }
public string Quantity { get; set; }
public double Location { get; set; }
}
What I need is to be able to update fields in the class with the following function.
Parameters:
- ac and pr define the keys and enable me to get an instance of the class.
- fld is the field name of the class to update. It could be “Position”, “Quantity” or “Location” or ??
- val is the value. It could be something like “London” or “1.234”
How can I arrange for the field name to be set dynamically without using a case statement to
check each value of fld and many different setters. Also if there’s some way of setting the field
dynamically how do I deal with casting it to the correct object type for that field?
public void Update(string ac, string pr, string fld, string val)
{
try
{
vm.Product = _product.Get(ac, pr);
vm.Product. xxx = fld
}
catch (Exception e) { log(e); }
}
Update
Here’s the solution proposed by Pieter:
public void Update(string ac, string pr, string fld, string val) {
try {
vm.Product = _product.Get("0000" + ac, pr);
if (vm.Product != null)
{
var property = vm.Product.GetType().GetProperty(fld);
var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
val = Convert.ChangeType(val, type);
property.SetValue(vm.Product, val, null);
}
_product.AddOrUpdate(vm.Product);
}
catch (Exception e) { log(e); }
}
You can use reflection:
SetValuerequires that the value is of the correct type. If this isn’t the case, you can convert it with the following:This automatically converts
valto the type of the property before assigning it.Note however that both using reflection and
Convert.ChangeTypeare horribly slow. If you do this a lot, you should have a look atDynamicMethod.