Ryan McBeth
Ryan McBeth
@RyanMcBethProgramming·1.1M subscribers·2K videos

How to describe Deep Copy and Shallow Copy for a job interview

Posted

July 5, 2021

Views

963

Likes

72

Comments

10

Engagement

8.52%

Search the Record

Indexed

Every word spoken in this episode is indexed. Type any phrase to jump straight to the moment it was said.

Type any word or phrase that may have been spoken. Click a result to seek the player to that exact moment.

Try a name, a topic, or a quoted line

YouTube Description

as posted by the channel

This is a "Gotcha" interview question because an interviewer may want to test your deep knowledge of how copying in C# and .NET works.

To start, the assignment or "=" operator does not actually make a copy. It only takes a new variable and references the memory location of the original value. If you change the original variable, the copy will also be changed because it is referencing the same place. This will result in some really strange bugs.

To make an genuine copy or clone, you need to perform a "Shallow Copy" by using the "MemberwiseClone()" method that is provided in .NET. However, this will only copy value types like integers, bools and floats. Although strings are reference types, they will "look copied" in a shallow copy because strings are immutable, so any changes to a string are placed in a new memory location when that string is created.

If you want to copy an object that also contains an object, you can perform a "Deep Copy." You will have to create custom code that creates new values and assigns them to a new cloned copy that is ultimately passed back.

You can also use .NET's built in Serialization and Deserialization functions, but make sure you need everything in the object before taking the performance and memory hit associated with that operation.

Source code available here:

ryanmcbeth.com

Music by Deal the Villian

Guests & Subjects Covered

Shallow CopyNET HoweverDeep Copy You

Sentinel Indexing in Progress

Metadata and chapters are available. Claim extraction for this episode is pending.

All video content is delivered via YouTube embedded players in accordance with the YouTube Terms of Service. Sentinel provides research tools that promote discovery and accountability across political media.

How to describe Deep Copy and Shallow Copy for a job interview · Ryan McBeth · Sentinel