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:

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:

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

List some different ways for equality check in .NET

junior

What is an Abstract Class?

senior

When to use ArrayList over array[] in C#?

Bình luận

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

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