+ Reply to Thread
Results 1 to 2 of 2

Thread: Mapping values between 2 objects

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    31

    Mapping values between 2 objects

    I want to map all properties that match between two class instances.
    Code:
    public class Candy
    {
        public bool A { get: set: }
        public bool B { get: set: }
        public bool C { get: set: }
        public bool D { get: set: }
        public bool E { get: set: }
    }
    
    public class Bar
    {
        public bool A { get: set: }
        public bool B { get: set: }
    }
    Bar bar = new Bar();
    bar.A = true;
    bar.B = true;
    How do I map the values from the bar instance to a new instance of Candy (setting the properties "A" and "B" to true)? I tried to make a method for it, but i get the exception Property set method not found..
    Code:
    public static void MapObjectPropertyValues(object e1, object e2)
        {
            foreach (var p in e1.GetType().GetProperties())
            {
                if (e2.GetType().GetProperty(p.Name) != null)
                {
                    p.SetValue(e1, e2.GetType().GetProperty(p.Name).GetValue(e2, null), null);
                }   
    
            }
        }

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    20
    I've implemented something similar to this before, here is the code :
    Code:
    public interface IHaveAAndB
    {
        bool A { get; set; }
        bool B { get; set; }
    }
    
    public class Foo : IHaveAAndB
    {     
        public bool A { get; set; }     
        public bool B { get; set; }     
        public bool C { get; set; }     
        public bool D { get; set; }     
        public bool E { get; set; } 
    }  
    
    public class Bar : IHaveAAndB
    {     
        public bool A { get; set; }     
        public bool B { get; set; } 
    } 
    
    public static void CopyInterfaceProperties<T>(T e1, T e2)     
    {         
        foreach (var prop in typeof(T).GetProperties())         
        {          
            if (prop.CanRead && prop.CanWrite)  
            {
                var value = prop.GetValue(e2, null)
                prop.SetValue(e1, value, null);   
            }
        }     
    }
    Just be sure to check the property can be read and written to before calling SetValue!

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts