Câu hỏi phỏng vấn C#
Câu hỏi

Explain assignment vs shallow copy vs deep copy for a Record in C#

Câu trả lời

Certainly! Here's an explanation of assignment, shallow copy, and deep copy for a Record in C#:

Assignment

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:

csharp Copy
var record1 = new Person("John", 30);
var record2 = record1;
record2 with { Name = "Jane" }; // Modifies both record1 and record2

Shallow Copy

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:

csharp Copy
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

middle

Gợi ý câu hỏi phỏng vấn

expert

Implement the Where method in C#. Explain

entry

What is C#?

senior

IEnumerable vs List - What to Use? How do they work?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào