Explain assignment vs shallow copy vs deep copy for a Record in C#
Explain assignment vs shallow copy vs deep copy for a Record in C#
Certainly! Here's an explanation of assignment, shallow copy, and deep copy for a Record in C#:
When you assign a Record instance to a new variable, it creates an alias to the original instance. Both variables point to the same instance in memory. Modifying the Record through one variable will affect the other variable as well.
Example:
var record1 = new Person("John", 30);
var record2 = record1;
record2 with { Name = "Jane" }; // Modifies both record1 and record2
A shallow copy creates a new Record instance with the same field values as the original instance. However, if the Record contains reference types (e.g., arrays, lists, or objects), the references are copied, not the actual values. This means that both the original and the copied instances share the same reference to the underlying object.
Example:
var record1 = new Person("John", 30, new Address("123 Main St", "Anytown"));
var record2 = record1 with { }; // Creates a shallow copy
record2 with { Address = new Address("456 Oak St", "Othertown") }; // Modifies only record2's address
In this example, modifying the Address
of record2
will not affect record1
because the Address
is a new instance. However, if you modify the Address
instance its...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào