Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone a generic type

Tags:

c#

generics

I want to clone a generic object and preserve its type.

run.Append(style.Clone(BlackFont)); //run object accepts only RunProperties objects

public T Clone(T what) {
    if (what is RunProperties)
        return (T) what.Clone();
}

It doesn't work since T type does not have a Clone method, how can I overcome this without casting in the first statement.

run.Append((RunProperties) style.Clone(BlackFont)); //I do not want this
//not that this will work since you can't convert T to RunProperties

Thanks for any help.

---EDIT---

It seems that it would be better for my not to use generics in this case. I'll split up the data.

like image 513
jn1kk Avatar asked Aug 30 '26 10:08

jn1kk


2 Answers

Here is a function I wrote that clones a record of type T, using reflection. This is a very simple implementation, I did not handle complex types etc.

public static T Clone<T>(T original)
{
    T newObject = (T)Activator.CreateInstance(original.GetType());

    foreach (var originalProp in original.GetType().GetProperties())
    {
        originalProp.SetValue(newObject, originalProp.GetValue(original));
    }

    return newObject;
}

I hope this can help someone.

like image 194
Assaf S. Avatar answered Aug 31 '26 22:08

Assaf S.


You could always constrain the method to only accept types that implement the ICloneable interface:

public T Clone(T what) where T : ICloneable
{
    if (what is RunProperties)
        return (T) what.Clone();
}

But since your method really only works with one type, you could change it slightly and use the as operator also:

public T Clone(T what)
{
    var castWhat = what as RunProperties;
    if(castWhat != null)
        return castWhat.Clone();
}
like image 33
Justin Niessner Avatar answered Aug 31 '26 23:08

Justin Niessner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!