When I create a copy of the original list lstStudent in lstCopy and send the lstCopy to modification function, the lstStudent also gets modified. I want to keep this list unmodified.
List<Student> lstStudent = new List<Student>();
Student s = new Student();
s.Name = "Akash";
s.ID = "1";
lstStudent.Add(s);
List<Student> lstCopy = new List<Student>(lstStudent);
Logic.ModifyList(lstCopy);
// "Want to use lstStudent(original list) for rest part of the code"
public static void ModifyList(List<Student> lstIntegers) {
foreach (Student s in lstIntegers) {
if (s.ID.Equals("1")) {
s.ID = "4"; s.Name = "APS";
}
}
}
You can also achieve this without cloneable interface by using binary formatter: NOTE: ALL classes as part of the object graph must be marked Serializable.
void Main()
{
var student1=new Student{Name="Bob"};
var student2=new Student{Name="Jim"};
var lstStudent=new List<Student>();
lstStudent.Add(student1);
lstStudent.Add(student2);
var lstCopy=new List<Student>(lstStudent);
var clone=Clone(lstStudent);
student1.Name="JOE";
lstCopy.Dump();
lstStudent.Dump();
clone.Dump();
}
public List<Student> Clone(List<Student> source)
{
BinaryFormatter bf=new BinaryFormatter();
using(var ms=new MemoryStream())
{
bf.Serialize(ms,source);
ms.Seek(0,0);
return (List<Student>)bf.Deserialize(ms);
}
}
[Serializable]
public class Student
{
public string Name { get; set; }
}
OUTPUT:
5List<Student> (2 items) 4
Name
JOE
Jim
5List<Student> (2 items) 4
Name
JOE
Jim
5List<Student> (2 items) 4
Name
Bob
Jim
code is formatted for dumping into LINQPad
EDIT:
This is an option in situations where it's not possible to implement ICloneable. When applicable, code to interfaces. In other words, you can implement ICloneable on the student object and use the BinaryFormatter logic in the Clone() method; However, As a developer, you have the option to decide for yourself what you want to do. Options are not necessarily advice and advice isn't always an option. There are times when you must do what it takes to complete a task and that's where options come into play.
This is a pretty widely accepted, deep cloning, method: How do you do a deep copy of an object in .NET (C# specifically)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With