Search code examples
c#propertyinfo

PropertyInfo SetValue doesn't set the Id of my object


I'm trying to make a function that allows me to map one class to another one. It's almost working, except that my Id property is not being mapped and I can't figure out why.

At the bottom there is a link to a coding example online, press F8 to run it. In the output you can see how the following code shows me the Id:

if(propertyInfo.Name == "Id")
    Console.WriteLine(propertyInfo.GetValue(currentEUser));

But when I try users.ForEach(u => Console.WriteLine(String.Format("{0}, {1}, {2}", u.Id, u.Name, u.Age)));, There are no Id's available. Why?

public class eUser
{
    public int Id {get;set;}
    public String Name {get;set;}
    public int Age {get { return 10;}}

    public eUser(int id, String name){
        Id = id;
        Name = name;
    }
}

public class User 
{
    public int Id {get;set;}
    public String Name {get;set;}
    public int Age {get { return 10;}}
}

I have my main program that should map all my fields from an eUser to a User object

public class Program
{

    public static void Main(string[] args)
    {
        // init
        List<User> users = new List<User>();
        User user = new User();

        List<eUser> eUsers = new List<eUser>();
        eUsers.Add(new eUser(1, "Joris"));
        eUsers.Add(new eUser(2, "Thierry"));
        eUsers.Add(new eUser(3, "Bert"));



        IList<PropertyInfo> eUserProps = new List<PropertyInfo>(eUsers.FirstOrDefault().GetType().GetProperties());
        foreach(eUser currentEUser in eUsers){

            foreach (PropertyInfo propertyInfo in eUserProps)
            {
                // Test to only map properties with a Set field
                if (propertyInfo.CanWrite)
                {
                    // Test to see if Id comes through
                    if(propertyInfo.Name == "Id")
                        Console.WriteLine(propertyInfo.GetValue(currentEUser));

                    // Create new user 
                    user = new User();

                    //Map eUser to User object
                    typeof(User)
                        .GetProperty(propertyInfo.Name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetField)
                        .SetValue(user, propertyInfo.GetValue(currentEUser));
                }

            }
            users.Add(user);

        }

        users.ForEach(u => Console.WriteLine(String.Format("{0}, {1}, {2}", u.Id, u.Name, u.Age)));
    }
}

Code example: http://rextester.com/SHNY15243


Solution

  • Move user = new User(); to outside of the 2nd foreach loop.