I have a two types that are very similar (i.e. the member names are very similar).
Is there an elegant way to copy one type to another, without having to copy each indi
See Copyable: A framework for copying or cloning .NET objects. Its slightly slower (it uses reflection), but it has one advantage: you can alter the source to handle corner cases where the member variables need a little bit of work to convert.
For example, in the sample source code in the question, member variable "ExpirationDate" is of type "DateTime" in one type, and type "IceDateTime" in the other (you need to convert the date format with the extension method .ToDateTime).
Here is the source (see the original blog entry for more source):
// Modification to original source code.
Type type = instance.GetType();
if (instance.GetType().Name == "DataTable")
{
// Added to handle custom type.
DataTable dt = (DataTable)instance;
copy = dt.Copy();
}
else if (instance.GetType().Name == "DataSet")
{
// Added to handle custom type.
DataSet ds = (DataSet)instance;
copy = ds.Copy();
}
else
{
// This is the original source.
while (type != null)
{
foreach (FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
object value = field.GetValue(instance);
if (visited.ContainsKey(value))
field.SetValue(copy, visited[value]);
else
field.SetValue(copy, value.Clone(visited));
}
type = type.BaseType;
}
}
return copy;
Use something like AutoMapper for that. It will allow you to simply define that class OptionsEnt
should be mapped to FromCsvFile
and if they have the properties with same names and types then you won't need to define anything else.
Otherwise you'll have to iterate by properties.
Maybe Automapper?
For example:
Mapper.CreateMap<FromCsvFile, OptionsEnt >();
return Mapper.Map<FromCsvFile, OptionsEnt>(fromCsvFile);