How to perform Shallow Copy in C# ?

Published on May 5, 2016 by abundantcode

Filed under C#

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 2932 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;
        Console.WriteLine(emp1.Name);
        Employee emp2 = emp1.ShallowCopy();
        Console.WriteLine(emp2.Name);
        Employee emp3 = emp1.ShallowCopy();
        emp1.LanguagesKnown = null;
        Console.WriteLine(emp3.Name);
    }
}
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


x

You might be Interested in these Posts

C# and Lambda – Filter elements from object collection with Logical Operators

Here’s a sample code snippet demonstrating how to filter elements from a list of objects using the w...

C# and LINQ – Filter elements from object collection with Logical Operators

Here’s a sample code snippet demonstrating how to filter elements from a list of objects using the w...

C# and Lambda – Filter elements from object collection using Where method

Here’s a sample code snippet demonstrating how to filter elements from a list of objects using the w...