0

Scenario: I have this class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

User has the ability to only select for example FirstName and Age.

Currently I am using reflection but I have been told that reflection hurts performance among other things.

public static class Helper<T>GetObject(List<string> fieldsToSet, Dictionary<string, string> values)
{
    var returnObject = new T();

    foreach (string field in fieldsToSet)
    {
        var property = returnObject.GetType().GetProperty(field);
        property.SetValue(returnObject, values[field], null);
    }        

    return returnObject;
}

Can anyone show me an example of how to do this (setting only a subset of all the fields in a class) using lightweight code generation?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Gustavo
  • 685
  • 3
  • 7
  • 17
  • @usr LINQ expressions are slow as well but they are way more elegant, one can also use something like https://github.com/AutoMapper/AutoMapper. – aybe Apr 04 '14 at 17:39
  • 1
    @Aybe the way to go is create an expression once, compile it and store a delegate to the compiled code. – usr Apr 04 '14 at 18:18
  • @usr Thanks for the tip, I'll give it a try in my application. – aybe Apr 04 '14 at 18:40

0 Answers0