Web Development

Shallow copy in C#

Shallow Copy: A shallow copy of an object copies all of the member field values. This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory. The pointer will be copied. but the memory it points to will not be copied — the field in both the original object and the copy will then point to the same dynamically allocated memory, which is not usually what you want. The default copy constructor and assignment operator make shallow copies.

// Program: Shallow Copy
// Purpose: Training period
// By: H.M. Saiful Islam

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ShallowCopy
{
    class Program
    {
        static void Main(string[] args)
        {
            Cloner mySource = new Cloner(5);
            Cloner myTarget = (Cloner)mySource.GetCopy();
            Console.WriteLine("value: {0}", myTarget.MyContent.Val);
            Console.ReadKey();
        }

        public class Content
        {
            public int Val;
        }

        public class Cloner
        {
            public Content MyContent = new Content();

            public Cloner(int newVal)
            {
                MyContent.Val = newVal;
            }

            public object GetCopy()
            {
                return MemberwiseClone();
            }
        }

    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s