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 6771665
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T15:27:32+00:00 2026-05-26T15:27:32+00:00

I have been creating object for a project and there are some instances that

  • 0

I have been creating object for a project and there are some instances that I have to create a deep copy for this objects I have come up with the use of a built in function for C# which is MemberwiseClone(). The problem that bothers me is whenever there is a new class that i created , I would have to write a function like the code below for a shallow copy..Can someone please help me improve this part and give me a shallow copy that is better than the second line of code. thanks 🙂

SHALLOW COPY:

public static RoomType CreateTwin(RoomType roomType)
{
    return (roomType.MemberwiseClone() as RoomType);
}

DEEP COPY:

public static T CreateDeepClone<T>(T source)
{
    if (!typeof(T).IsSerializable)
    {
        throw new ArgumentException("The type must be serializable.", "source");
    }

    if (Object.ReferenceEquals(source, null))
    {
        return default(T);
    }

    IFormatter formatter = new BinaryFormatter();
    Stream stream = new MemoryStream();
    using (stream)
    {
        formatter.Serialize(stream, source);
        stream.Seek(0, SeekOrigin.Begin);
        return (T)formatter.Deserialize(stream);
    }
}
  • 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-05-26T15:27:33+00:00Added an answer on May 26, 2026 at 3:27 pm

    MemberwiseClone is not a good choice to do a Deep Copy (MSDN):

    The MemberwiseClone method creates a shallow copy by creating a new
    object, and then copying the nonstatic fields of the current object to
    the new object. If a field is a value type, a bit-by-bit copy of the
    field is performed. If a field is a reference type, the reference is
    copied but the referred object is not
    ; therefore, the original
    object and its clone refer to the same object.

    This mean if cloned object has reference type public fields or properties they would reffer to the same memory location as the original object’s fields/properties, so each change in the cloned object will be reflected in the initial object. This is not a true deep copy.

    You can use BinarySerialization to create a completely independent instance of the object, see MSDN Page of the BinaryFormatter class for an serialization example.


    Example and Test Harness:

    Extension method to create a deep copy of a given object:

    public static class MemoryUtils
    {
        /// <summary>
        /// Creates a deep copy of a given object instance
        /// </summary>
        /// <typeparam name="TObject">Type of a given object</typeparam>
        /// <param name="instance">Object to be cloned</param>
        /// <param name="throwInCaseOfError">
        /// A value which indicating whether exception should be thrown in case of
        /// error whils clonin</param>
        /// <returns>Returns a deep copy of a given object</returns>
        /// <remarks>Uses BInarySerialization to create a true deep copy</remarks>
        public static TObject DeepCopy<TObject>(this TObject instance, bool throwInCaseOfError)
            where TObject : class
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
    
            TObject clonedInstance = default(TObject);
    
            try
            {
                using (var stream = new MemoryStream())
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    binaryFormatter.Serialize(stream, instance);
    
                    // reset position to the beginning of the stream so
                    // deserialize would be able to deserialize an object instance
                    stream.Position = 0;
    
                    clonedInstance = (TObject)binaryFormatter.Deserialize(stream);
                }
            }
            catch (Exception exception)
            {
                string errorMessage = String.Format(CultureInfo.CurrentCulture,
                                "Exception Type: {0}, Message: {1}{2}",
                                exception.GetType(),
                                exception.Message,
                                exception.InnerException == null ? String.Empty :
                                String.Format(CultureInfo.CurrentCulture,
                                            " InnerException Type: {0}, Message: {1}",
                                            exception.InnerException.GetType(),
                                            exception.InnerException.Message));
                Debug.WriteLine(errorMessage);
    
                if (throwInCaseOfError)
                {
                    throw;
                }
            }
    
            return clonedInstance;
        }
    }
    

    NUnit tests:

    public class MemoryUtilsFixture
    {
        [Test]
        public void DeepCopyThrowWhenCopyInstanceOfNonSerializableType()
        {
            var nonSerializableInstance = new CustomNonSerializableType();
            Assert.Throws<SerializationException>(() => nonSerializableInstance.DeepCopy(true));
        }
    
        [Test]
        public void DeepCopyThrowWhenPassedInNull()
        {
            object instance = null;
            Assert.Throws<ArgumentNullException>(() => instance.DeepCopy(true));
        }
    
        [Test]
        public void DeepCopyThrowWhenCopyInstanceOfNonSerializableTypeAndErrorsDisabled()
        {
            var nonSerializableInstance = new CustomNonSerializableType();            
            object result = null;
    
            Assert.DoesNotThrow(() => result = nonSerializableInstance.DeepCopy(false));
            Assert.IsNull(result);
        }
    
        [Test]
        public void DeepCopyShouldCreateExactAndIndependentCopyOfAnObject()
        {
            var instance = new CustomSerializableType
                            {
                                DateTimeValueType =
                                    DateTime.Now.AddDays(1).AddMilliseconds(123).AddTicks(123),
                                NumericValueType = 777,
                                StringValueType = Guid.NewGuid().ToString(),
                                ReferenceType =
                                    new CustomSerializableType
                                        {
                                            DateTimeValueType = DateTime.Now,
                                            StringValueType = Guid.NewGuid().ToString()
                                        }
                            };
    
            var deepCopy = instance.DeepCopy(true);
    
            Assert.IsNotNull(deepCopy);
            Assert.IsFalse(ReferenceEquals(instance, deepCopy));
            Assert.That(instance.NumericValueType == deepCopy.NumericValueType);
            Assert.That(instance.DateTimeValueType == deepCopy.DateTimeValueType);
            Assert.That(instance.StringValueType == deepCopy.StringValueType);
            Assert.IsNotNull(deepCopy.ReferenceType);
            Assert.IsFalse(ReferenceEquals(instance.ReferenceType, deepCopy.ReferenceType));
            Assert.That(instance.ReferenceType.DateTimeValueType == deepCopy.ReferenceType.DateTimeValueType);
            Assert.That(instance.ReferenceType.StringValueType == deepCopy.ReferenceType.StringValueType);
        }
    
        [Serializable]
        internal sealed class CustomSerializableType
        {            
            public int NumericValueType { get; set; }
            public string StringValueType { get; set; }
            public DateTime DateTimeValueType { get; set; }
    
            public CustomSerializableType ReferenceType { get; set; }
        }
    
        public sealed class CustomNonSerializableType
        {            
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have been creating Unit tests like crazy and find that I'm often having
I have been creating a peer to peer connection for a new game, that
I have been tasked with creating a program that will generate an amortization schedule.
I have been tasked with creating a program what will create take files in
I have been reading that creating dependencies by using static classes/singletons in code, is
In the past years I have been working on different projects that required creating
I have recently started work on a project that has already been running for
I have been creating a website with Ruby on Rails, and will be hosting
I have been creating an image gallery with jQuery, all is done. The images
So far I have been creating Web Portal but recently I had a request

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.