tags:

views:

71

answers:

3

I have the following classes:

public abstract class Item
{
    //...
}

public class Customer : Item
{
    //...
}

public class Address : Item
{      
    //...
}

I want to be able to create exact clones using a custom reflection class like this:

Customer customer = new Customer();
ItemReflector irCustomer = new ItemReflector(customer);
Customer customerClone = irCustomer.GetClone<Customer>();

But I'm having trouble with the syntax of the GetClone method:

public class ItemReflector
{
    private Item item;

    public ItemReflector(Item item)
    {
        this.item = item;
    }

    public Item GetClone<T>()
    {
        T clonedItem = new T();
        //...manipulate the clonedItem with reflection...
        return clonedItem;
    }
}

What do I have to change to the above GetClone() method so that it works?

+6  A: 

You need a new constraint if you want to be able to instantiate T:

public Item GetClone<T>() where T: new()
{
    T clonedItem = new T();
    //...manipulate the clonedItem with reflection...
    return clonedItem;
}
Darin Dimitrov
perfect, thanks.
Edward Tanguay
A: 

Look at my answer on Why no ICloneable ?

TcKs
A: 

Since GetClone() is returning Item then presumably the constraint is that T is a sub class of Item.

Also since ItemReflector doesn't seem to need state GetClone() should be static.