Sunday, April 05, 2009

Clone an object in C# using reflection for system and generic types

public object Clone()
{
object newObject = Activator.CreateInstance(GetType());
PropertyInfo[] propertyInfos = GetType().GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
if (propertyInfo.PropertyType.IsGenericType)
{
if (propertyInfo.PropertyType.GetInterface("IList", true) != null)
{
IList oldList = propertyInfo.GetValue(this, null) as IList;
if (oldList != null && oldList.Count > 0 &&
oldList[0].GetType().GetInterface("ICloneable", true) != null)
{
IList newList = (IList)propertyInfo.GetValue(newObject, null);
foreach (object obj in oldList)
{
ICloneable clone = (ICloneable)obj;
newList.Add(clone.Clone());
}
}
else
{
propertyInfo.SetValue(newObject, oldList, null);
}
}
if (propertyInfo.PropertyType.GetInterface("IDictionary", true) != null)
{
IDictionary oldDic =
propertyInfo.GetValue(this, null) as IDictionary;
if (oldDic != null && oldDic.Count > 0 &&
oldDic[0].GetType().GetInterface("ICloneable", true) != null)
{
IDictionary newDic =
(IDictionary)propertyInfo.GetValue(newObject, null);
foreach (DictionaryEntry entry in oldDic)
{
ICloneable clone = (ICloneable)entry.Value;
newDic[entry.Key] = clone.Clone();
}
}
else
{
propertyInfo.SetValue(newObject, oldDic, null);
}
}
}
else
{
//Clone IClonable object
if (propertyInfo.GetType().GetInterface("ICloneable", true) != null)
{
ICloneable clone = (ICloneable)propertyInfo.GetValue(this, null);
propertyInfo.SetValue(newObject, clone.Clone(), null);
}
else
{
propertyInfo.SetValue(
newObject, propertyInfo.GetValue(this, null), null);
}
}
}
return newObject;
}



No comments: