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 4035 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);
    }
}

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

How to get the AM or PM value from a DateTime object in C# ?

There are times when you might want to get only the string AM or PM from the DateTime object that yo...

C# Program to swap two numbers without using temporary variable

Problem Write a program in Visual CSharp to swap two numbers using temporary variable and display t...

C# Program to print the sum of two numbers

Problem Write a program in C# to add two numbers and display the result in copnsole window. How to...