0

I have a class that have value types and some List<Object> members. The class implements IClonable interface and Clone() and GetHashCode() are implemented. In Clone() method I used MemberwiseClone() method for cloning value types.

I also did same coding in Object (lets call it Person) class. I want to call that class's Clone() method in the referrer class's Clone() method. But because of the type of the class here is Object I can't call Clone() method of it.

I can't make Object to Person here because the type of Object changes at runtime. Sometimes it is 'Person' sometimes 'Order' for example.

Here is example code:

public class Person : IClonable
{
    public string name = "Name";
    public string surname = "Surname";

    public override Person Clone()
    {
        Person p = this.MemberwiseClone();
    }
}

public class Order : IClonable
{
    public string name = "OrderName";
    public int orderId = 1;

    public override Order Clone()
    {
        Person p = this.MemberwiseClone();
    }
}

public class List : IClonable
{
    public string listname = "ListName";
    List<object> objectList = new List<object>();

    public override List Clone()
    {
        List l = this.MemberwiseClone(); //This clones value types

        List<object> copyObjectList = new List(object);

        foreach(Object o in objectList)
        {
            Object co = o.Clone(); //I want something like this
            copyObjectList.Add(co);
        }

        l.objectList = copyObjectList;

        return l;
    }
}
Murat
  • 35
  • 7

1 Answers1

0

Not sure I fully understand your question... but are you after something like this?

List<Object> objects = GetListOfObjects();
foreach(var obj in objects) 
{
    if ((var cloneMeQuick = obj as IClonable)) { //or `obj as Person` if you only want to go deep on person objects
        yield return cloneMeQuick.Clone();
    }
}
JohnLBevan
  • 22,735
  • 13
  • 96
  • 178