Monday, May 2, 2011

Deep Clone in C#

Are you trying to do deep clone of the object in c#? Following one more way to clone object:

public object Clone( object item)
{
  if (item == null)
        return null;
 if (item is System.Runtime.Serialization.ExtensionDataObject)
        return null;
  if (item is Entity)
  {
      Entity source = item as Entity;
      Entity result = new Entity(source.LogicalName);
      object value;
      foreach (KeyValuePair<stringobject> pair in source.Attributes)
      {
  value = Clone( pair.Value);
 result.Attributes.Add(pair.Key, value);
      }
      return result;
   }
   else
   {
      if (item is ICloneable)
      {
         ICloneable toclone = item as ICloneable;
         object result = toclone.Clone();
         return result;
      }
      else if ( item is Guid)
      {
         return new Guid(item.ToString());                
      }
else
      {
        Type type = item.GetType();
         PropertyInfo[] properties = type.GetProperties();
         object result = null;
         try 
         {
             result = Activator.CreateInstance(type);
             object value;
             object clonedValue;
             foreach (PropertyInfo prop in properties)
            {
                 clonedValue = null;
                 if (prop.CanWrite)
                 {
                    value = prop.GetValue(item, null);
                    if (value != null)
                    {
                       if (prop.PropertyType == typeof(string))
                       {
                          string newstring = value.ToString();
                          clonedValue = newstring;
                  }
else if (prop.PropertyType.IsClass) 
                     {
                         clonedValue = Clone(value);
                }
if (clonedValue != null)
                   prop.SetValue(result, clonedValue, null);
                     else
                        prop.SetValue(result, value, null);
              }
      }
        }                                }  
        catch (Exception ex)
        {
        // Nothing to do
        }
        return result;
    }
 }

No comments:

Post a Comment