1

My goal is to reduce the code and avoid having to add conditions when my passed list of object gets longer, it can be up to 100+ fields as the project progresses. I have an object of type MyObject

public class MyObject
{
    public string fininstId { get; set; }
    public string paymentMethod { get; set; }
    public string cardNumber { get; set; }
    public string cardExpiry { get; set; }
    public string cardCVC { get; set; }
    public string AcctName { get; set; }
    public string Password { get; set; }
    public string mode { get; set; }
}

another one of type Response

public class Response
{
    public Response();

    public string Title { get; set; }
    public string Value { get; set; }
}

and I need all of the data contained in dataList below to be copied to MyObject, knowing that the name of the fields are going to be the same in both MyObject and dataList.

List<Response> dataList = new List<Response>();

/*...populating dataList here ...*/

MyObject request = new MyObject();

foreach (var item in dataList)
{
    switch (item.Title)
    {
        case "cardNumber":
            request.cardNumber = item.Value;
            break;
        case "cardExpiry":
            request.cardExpiry = item.Value;
            break;
        case "cardCVC":
            request.cardCVC = item.Value;
            break;
        case "fininstId":
            request.fininstId = item.Value;
            break;
        case "paymentMethod":
            request.paymentMethod = item.Value;
            break;
        case "AcctName":
            request.AcctName = item.Value;
            break;
        case "Password":
            request.Password = item.Value;
            break;
    }
}

Is there anyway it can be done dynamically?

ekad
  • 14,436
  • 26
  • 44
  • 46
Billy Blaze
  • 107
  • 9
  • You can use Reflection to reduce the amount of code to something that just matches the Title string to a property name, but it won't perform near as well. – Joel Coehoorn Jun 20 '16 at 15:42
  • You can [use reflection to find a property that matches the string in `Title`](http://stackoverflow.com/questions/7718792). The conditions you need to account for are: "what if the property does not exist?" and "How do I handle type conversion?". Neither of those has a trivial answer. – D Stanley Jun 20 '16 at 15:44

1 Answers1

3

You can use reflection and InvokeMember method

For example:

Response item = new Response();
item.Title = "Password";
item.Value = "value";

MyObject request = new MyObject();
request.GetType().InvokeMember(item.Title,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder, request, new[] {item.Value} );

Or using GetProperty & SetValue

var property = typeof(MyObject).GetProperty(item.Title);
property.SetValue(request, item.Value, null);
Valentin
  • 5,380
  • 2
  • 24
  • 38