This seems like a very simple question but I just can not figure it
out. I would like assign all property values of class Y to class X. I
can NOT do X=Y.
Ignoring the code, here is a basic translator, if you will. You can add
in the generics, but this is a very simple example.
Assume the following:
public class User
{
public User(string firstName, string lastName, string address1
, string address2, string city, string stateProvince
, string postalCode)
{
FirstName = firstName;
LastName = lastName;
Address1 = address1;
Address2 = address2;
City = city;
StateProvince = stateProvince;
PostalCode = postalCode;
}
public string FirstName{ get; set; }
public string LastName{ get; set; }
public string Address1{ get; set; }
public string Address2{ get; set; }
public string City{ get; set; }
public string StateProvince{ get; set; }
public string PostalCode{ get; set; }
}
public class Customer
{
//Constructor not needed for example
public string FName{ get; set; }
public string LName{ get; set; }
public string Addr1{ get; set; }
public string Addr2{ get; set; }
public string City{ get; set; }
public string State{ get; set; }
public string ZipCode{ get; set; }
}
You set up user but want customer filled. Here is a simple routine that
has a dictionary to translate (could easily be XML):
class Program
{
static void Main(string[] args)
{
//Just for mapping
Dictionary<string, string> dict =
new Dictionary<string, string>();
dict.Add("FirstName", "FName");
dict.Add("LastName", "LName");
dict.Add("Address1", "Addr1");
dict.Add("Address2", "Addr2");
dict.Add("StateProvince", "State");
dict.Add("PostalCode", "ZipCode");
//Create user
User user = new User("Greg", "Beamer"
, "1234 Any Street", null
, "Nashville", "TN", "37221");
Customer customer = new Customer();
//Get types of objects
Type originalType = user.GetType();
Type newType = customer.GetType();
//Get original properties
PropertyInfo[] info = originalType.GetProperties();
//Iterate properties
for (int i = 0; i < info.Length; i++)
{
//Pull current working property
PropertyInfo oldProperty = info
;
//Get its value
object o = oldProperty.GetValue(user, null);
//Find mapped name (this assumes some names
//not mapped, as they are equivalent (City)
string propName;
if(dict.ContainsKey(oldProperty.Name))
propName = dict[oldProperty.Name];
else
propName = oldProperty.Name;
//Pull new property
PropertyInfo newProperty =
newType.GetProperty(propName);
//Set value
newProperty.SetValue(customer, o, null);
}
Console.Read();
}
}
This is overly bloated, as it is designed to break everything down, but
any two types that can be mapped can be set. If you want to further use
generics to avoid boxing and unboxing (when using value types), you can
add that. If you test this code, you will find it moves everything just
fine, even if it is not the most efficient method of doing it.