Advertisement
elena1234

Deep Copy vs Shallow Copy in C#

Dec 10th, 2021 (edited)
1,235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.19 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Delegates
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             var firstStudent = new Student("Gosho Goshev", 1000, new Grade ("Good", 4 ));
  10.             var secondStudent = new Student("Ana Ivanova", 2000, new Grade("Very Good", 5));
  11.  
  12.             //secondStudent = firstStudent.ShallowCopy();
  13.             //secondStudent.Grade.Name = "Exellent";
  14.             //secondStudent.Grade.Value = 6;
  15.             // Console.WriteLine($"{firstStudent.Name} {firstStudent.ID} {firstStudent.Grade.Value}"); // Gosho Ivanov, 1000, but grade is also 6 like grade in secondStudent
  16.  
  17.             // With Deep Copy we can copy all of the value types and we create new references in the secondStudent
  18.             secondStudent = firstStudent.DeepCopy();
  19.             secondStudent.Grade.Name = "Exellent";
  20.             secondStudent.Grade.Value = 6;
  21.             Console.WriteLine($"{firstStudent.Name} {firstStudent.ID} {firstStudent.Grade.Value}"); // // Gosho Ivanov, 1000, 4 is not changed after the changes in secondStudent
  22.  
  23.         }
  24.  
  25.         public class Student
  26.         {
  27.             public Student(string name, int iD, Grade grade)
  28.             {
  29.                 this.Name = name;
  30.                 this.ID = iD;
  31.                 this.Grade = grade;
  32.             }
  33.  
  34.             public string Name { get; set; }
  35.             public int ID { get; set; }
  36.             public Grade Grade { get; set; }
  37.  
  38.            
  39.             public Student ShallowCopy()
  40.             {
  41.                 Student tempObject = (Student) this.MemberwiseClone();
  42.                 return tempObject;
  43.             }
  44.  
  45.             public Student DeepCopy()
  46.             {
  47.                 Grade gradeCopy = new Grade(this.Grade.Name, this.Grade.Value);
  48.                 Student newStudent = new Student(this.Name, this.ID, gradeCopy); // we have a constructor
  49.                 return newStudent;
  50.             }
  51.  
  52.         }
  53.  
  54.     }
  55.  
  56.     public class Grade
  57.     {
  58.         public Grade(string name, int value)
  59.         {
  60.             this.Name = name;
  61.             this.Value = value;
  62.         }
  63.  
  64.         public string Name { get; set; }
  65.         public int Value { get; set; }
  66.     }
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement