Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8686357
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T22:49:39+00:00 2026-06-12T22:49:39+00:00

The ICloneable interface of the .NET framework usually provides a way to support cloning

  • 0

The ICloneable interface of the .NET framework usually provides a way to support cloning of an instance of a class.

But if I have multiple 3rd party classes, and don’t want to care about each of the properties individually, how can I clone objects of those classes efficiently? (The source code of those classes is not available).
Is there a way using generics and extension methods?

What I need is a deep clone which creates an exact copy including all the properties and (child) objects.


Example: Suppose you want to clone a UserQuery object in LinqPad:

void Main()
{
    UserQuery uc=this;
    var copy=uc.CreateCopy(); // clone it
}

What I am looking for is a CreateCopy() extension that allows to create a copy without having to take care of the details of this class since I don’t own the source of UerQuery.

(Note that UserQuery is just an example to show what I require, it could as well be a PDF document class, a user control class, a ADO.NET class or anything else).

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T22:49:40+00:00Added an answer on June 12, 2026 at 10:49 pm

    I have currently 2 different solutions for this, one with and one without the use of reflection:


    1.) With a generic extension method (plus reflection) you can do it this way in C#:

    public static class Extension
    {
        public static T CreateCopy<T>(this T src)
            where T: new()
        {
            if (src == null) return default(T); // just return null
            T tgt = new T(); // create new instance
            // then copy all properties
            foreach (var pS in src.GetType().GetProperties())
            {
                foreach (var pT in tgt.GetType().GetProperties())
                {
                    if (pT.Name != pS.Name) continue;
                    (pT.GetSetMethod()).Invoke(tgt, new object[] { 
                        pS.GetGetMethod().Invoke(src, null) });
                }
            };
            return tgt;
        } // method
    } // class
    

    This is very powerful, because now you can clone every object, not just objects from the classes you have written, but from all classes including the system classes of the .NET Framework. And thanks to reflection, you don’t need to know its properties, they are copied automatically.

    Example

    To use the method CreateCopy(), let’s say you have a Customer class and a Order class, and you need to create copies (not references) but with new IDs. Then you can do the following:

    Order CopyOrderWithNewPK(Order item)
    {
        Order newItem = item.CreateCopy(); // use ext. method to copy properties
        newItem.OrderId = new Guid(); // create new primary key for the item
        return newItem;
    }
    

    Not surprisingly, for the Customer class it would look the same:

    Customer CopyCustomerWithNewPK(Customer item)
    {
        Customer newItem = item.CreateCopy(); // use ext. method to copy properties
        newItem.CustomerId = new Guid(); // create new primary key for the item
        return newItem;
    }
    

    Note that the values of all properties defined within the example classes are copied automatically. You can even clone an object of a 3rd party assembly if you don’t own the source code. The trade-off is, that the reflection approach is slower.


    2.) There’s another another way to do it without reflection, inspired by this question. One advantage is that it even is able to clone the objects of the Entity Framework (for example to attach and re-attach entity objects to a different data context):

    // using System.Runtime.Serialization;
    public class Cloner<T>
    {
        readonly DataContractSerializer _serializer 
                = new DataContractSerializer(typeof(T));
    
        /// <summary>
        /// Clone an object graph
        /// </summary>
        /// <param name="graph"></param>
        /// <returns></returns>
        public T Clone(T graph)
        {
            MemoryStream stream = new MemoryStream();
            _serializer.WriteObject(stream, graph);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)_serializer.ReadObject(stream);
        }
    }
    

    In order to not break the examples above, you can change the extension method CreateCopy as follows:

    public static class Extension
    {   
        public static T CreateCopy<T>(this T src)
            where T: new()
        {
                return (new Cloner<T>()).Clone(src);
        }   
    }   
    

    Note: Although Cloner is using System.Runtime.Serialization, the object being cloned does not need to be serializable. This can be an advantage, other solutions I have seen can only clone serializable objects.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

If a Java class implements the Serializable interface but does not have a public
interface ICloneable<out T> { T Clone(); } class Base : ICloneable<Base> { public Base
I try to create a generic interface that inherits the System.ICloneable interface but where
I have a class (simplified example) like : public class SomeCollection : ICloneable {
I have the following: public class InstanceList : List<Instance> {} I would like to
I have this class : public class Person : ICloneable { public string FirstName
I have the following class hierarchy: public class Row : ICloneable, IComparable, IEquatable<Row>, IStringIndexable,
I was looking at code that implemented the ICloneable interface for one of the
The use case is some what like this: public class SomeClass : ICloneable {
The Java documentation says: A class implements the Cloneable interface to indicate to the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.