How to perform Shallow Copy in C# ?

Published on May 5, 2016 by abundantcode

Filed under Foundation (General)

Last modified May 5, 2016

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 1 (1 votes)

This article have been viewed 1547 times

To perform Shallow copy in C# , you can use the this.MemberwiseClone() method.

How to perform Shallow Copy in C# ?

Below is a sample code snippet that contains a method ShallowCopy to make a copy of the object.

public class Employee 
    public int Id { get; set; }

    public string Name { get; set; }
    public List<Languages> LanguagesKnown { get; set; } 

    public Employee ShallowCopy()
        return (Employee)this.MemberwiseClone();

public class Languages
    public string Name { get; set; }

class Program
    static void Main(string[] args)
        Employee emp1 = new Employee();
        emp1.Id = 1;
        emp1.Name = "Abundantcode Developer1";
        List<Languages> programmingLanguages = new List<Languages>();
        programmingLanguages.Add(new Languages {Name = "JavaScript"});
        programmingLanguages.Add(new Languages { Name = "C#" });
        emp1.LanguagesKnown = programmingLanguages;
        Employee emp2 = emp1.ShallowCopy();
        Employee emp3 = emp1.ShallowCopy();
        emp1.LanguagesKnown = null;
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

1 Comment

  1. How to perform Shallow Copy in C# ? by @abundantcode | Ginktage
    May 5, 2016 - 10:30 pm

Leave a Comment


You might be Interested in these Posts

How to Get the number of elements in ArrayList in C# ?

Here's the code that demonstrates how one can get the total number of elements contained in the Arra...

How to Check if the ArrayList is read-only in C# ?

There are times when you would use the read-only wrapper in order to prevent modifying the ArrayList...

How to Add range of elements to ArrayList in C# ?

You can use the AddRange method of the ArrayList object to add the range of elements (string array) ...