Deep Copy vs Shallow Copy in C#
using System;
namespace Delegates
{
class Program
{
static void Main(string[] args)
{
var firstStudent = new Student("Gosho Goshev", 1000, new Grade ("Good", 4 ));
var secondStudent = new Student("Ana Ivanova", 2000, new Grade("Very Good", 5));
//secondStudent = firstStudent.ShallowCopy();
//secondStudent.Grade.Name = "Exellent";
//secondStudent.Grade.Value = 6;
// Console.WriteLine($"{firstStudent.Name} {firstStudent.ID} {firstStudent.Grade.Value}"); // Gosho Ivanov, 1000, but grade is also 6 like grade in secondStudent
// With Deep Copy we can copy all of the value types and we create new references in the secondStudent
secondStudent = firstStudent.DeepCopy();
secondStudent.Grade.Name = "Exellent";
secondStudent.Grade.Value = 6;
Console.WriteLine($"{firstStudent.Name} {firstStudent.ID} {firstStudent.Grade.Value}"); // // Gosho Ivanov, 1000, 4 is not changed after the changes in secondStudent
}
public class Student
{
public Student(string name, int iD, Grade grade)
{
this.Name = name;
this.ID = iD;
this.Grade = grade;
}
public string Name { get; set; }
public int ID { get; set; }
public Grade Grade { get; set; }
public Student ShallowCopy()
{
Student tempObject = (Student) this.MemberwiseClone();
return tempObject;
}
public Student DeepCopy()
{
Grade gradeCopy = new Grade(this.Grade.Name, this.Grade.Value);
Student newStudent = new Student(this.Name, this.ID, gradeCopy); // we have a constructor
return newStudent;
}
}
}
public class Grade
{
public Grade(string name, int value)
{
this.Name = name;
this.Value = value;
}
public string Name { get; set; }
public int Value { get; set; }
}
}