C
C#5mo ago
arch_il

✅ How to force C# to copy data?

I am trying to debug code and I have a list of rooms and another list of backup_rooms. They both get initialized at the same time, but when I need use backup room I find that is has changed (It is never used in code). My guess is, that a reference is created to an object rather than a copy of it. So how to force C# to copy?
7 Replies
Jimmacle
Jimmacle5mo ago
do you have an example of your code? in general yes, reference types (classes) work similarly to passing pointers around in C/C++
arch_il
arch_il5mo ago
public static void ReloadRooms()
{
using (System.IO.StreamReader sr = new System.IO.StreamReader("Rooms.json"))
{
GlobalValues.rooms.Clear();

var data = JsonSerializer
.Deserialize<JsonReceiver>(
sr.ReadToEnd(),
new JsonSerializerOptions { IncludeFields = true }
).ParseData();

checkpoints = data.Item1;
rooms = backup_rooms = data.Item2;
}
}
public static void ReloadRooms()
{
using (System.IO.StreamReader sr = new System.IO.StreamReader("Rooms.json"))
{
GlobalValues.rooms.Clear();

var data = JsonSerializer
.Deserialize<JsonReceiver>(
sr.ReadToEnd(),
new JsonSerializerOptions { IncludeFields = true }
).ParseData();

checkpoints = data.Item1;
rooms = backup_rooms = data.Item2;
}
}
Jimmacle
Jimmacle5mo ago
so if you're creating a room and adding it to both lists, they're referencing the same room object
arch_il
arch_il5mo ago
is there a function for creating a deep copy of an object or do I have to make a new object myself?
Jimmacle
Jimmacle5mo ago
you have to make a copy yourself, there's no built in function for that because exactly what a "deep copy" is depends on the object
arch_il
arch_il5mo ago
this is the part where the reference is created. thanks
MKP
MKP5mo ago
I would use copy constructors to aid you in your quest
Want results from more Discord servers?
Add your server
More Posts