I have two objects that contain some properties that are exactly the same (same name, type). What I want to do is populate one object's identical properties with another object's properties. I am trying to do this in code, but it's not working. The Bin object's properties are not being set.
class Basket{
public Basket(int itemId, int itemGroup){
ItemId=itemId;
ItemGroup=itemGroup;
}
private int _itemId;
private int _itemGroup;
public int ItemId{ get{return _itemId;} set{_itemId = value};}
public int ItemGroup{ get{return _itemGroup;} set{_itemGroup = value};}
}
struct Bin{
public string Name;
private int _itemId;
private int _itemGroup;
public int ItemId{ get{return _itemId;} set{_itemId = value};}
public int ItemGroup{ get{return _itemGroup;} set{_itemGroup = value};}
public bool IsEmpty;
}
Basket basket = new Basket(1,1);
Bin bin = new Bin();
PropertyInfo[] basketPI = basket.GetType().GetProperties();
PropertyInfo[] binPI = bin.GetType().GetProperties();
foreach(PropertyInfo biPI in binPI){
foreach(PropertyInfo baPI in basketPI){
if(baPI.Name==biPI.Name){
biPI.SetValue(bin,baPI.GetValue(basket,null),null));
}
}
}
I'm trying to get away from simply doing:
object1.ItemId = object2.ItemId;
object1.ItemGroup = object2.ItemGroup;
I'm also wondering if there is a more elegant way to do this?
EDIT: I shorthanded the classes; meant to have the get/set in there.
EDIT: Changed to struct from object. For some reason it doesn't like setting the struct's properties when I do this.