Code Tips

C# MemberwiseClone

Clone Trooper - Creative Commons License from https://c2.staticflickr.com/4/3484/3796528975_e8c7faaed2_z.jpg?zz=1

If you’ve ever needed to make a copy of an object in C#, you might have come across the MemberwiseClone() method. This can save you a lot of hassle of left-hand/right-hand property matching, but it does come with some “gotchas” that might not be readily apparent if you haven’t carefully read the documentation.

Let’s start with a class that looks like this. Notice that it has a ShallowCopy method that just returns a MemberwiseClone of the object.

public class Person
    {
        public string Name { get; set; }
        public Person Boss { get; set; }

        public Person ShallowCopy()
        {
            return (Person)this.MemberwiseClone();
        }
    }

Now, let’s create some objects and make a shallow copy of the worker and see if the objects are the same:

Person bigBoss = new Person() { Name = "Tony", Boss = null };
Person boss = new Person() { Name = "Silvio", Boss = bigBoss };
Person worker = new Person() { Name = "Paulie", Boss = boss };

Person cloneWorker = worker.ShallowCopy();
Console.WriteLine("Are the workers the same? {0}", worker.Equals(cloneWorker));
Console.WriteLine("Are the bosses the same? {0}", worker.Boss.Equals(cloneWorker.Boss));

This gives us the following results:

Are the workers the same? False
Are the bosses the same? True

“So what?” you might ask. Well, what that means is that if I change a property on the Boss of either object, it automatically changes in the other object (since only the reference was copied, and that reference points to the same memory address in both cases).

worker.Boss.Name = "Chuck";
Console.WriteLine("Worker's Boss' Name: {0}.", worker.Boss.Name);
Console.WriteLine("Clone Worker's Boss' Name: {0}.", cloneWorker.Boss.Name);

This gives us the output:

Worker's Boss' Name: Chuck.
Clone Worker's Boss' Name: Chuck.

It is possible that you may be okay with this happening. However, if you don’t want this to happen, you can implement a DeepCopy on your object instead. In the DeepCopy, you take a MemberwiseClone and then you call for a deep copy on every reference type in the object. In our example, I’d add this to our Person class:

public Person DeepCopy()
{
    Person copy = (Person)this.MemberwiseClone();

    if (this.Boss != null)
    {
        copy.Boss = this.Boss.DeepCopy();
    }

    return copy;
}

Now, when I check on the objects, they aren’t the same. And, when we change the property on the boss, it doesn’t automatically change in both places because they are completely separate objects.

Are the workers the same? False
Are the bosses the same? False

Worker's Boss' Name: Chuck.
Clone Worker's Boss' Name: Silvio.

That’s all there is to it. I have wrapped up the code for this blog post into a small console project and put it on GitHub. If you have any questions, let me know in the comments.

Podcasts

Podcast Episode 21 – Enough with the Religious Bigotry

Larry Wall Bigotry Quote

In Episode 21, I spend a little time on the “significance” of episode 21 before getting into the main topic. Our topic this time is about people who worship the language that they are using like a religion. Far too often, I’ve encountered the attitude from developers that people who aren’t using what they are using are luddites, heretics, and not worth their time. In my opinion, that has no place in today’s development landscape and I explain why.

Links Mentioned in this Show:

You can also subscribe to the podcast at any of these places:
iTunes Link RSS Feed

Thanks to all the people who listen, and a special thanks to those who have rated me. I really appreciate it.

The episodes have been archived. Click Here to see the archive page.

Personal

My First Guest Post – a Brief Bio of John W Mauchly

A little over two weeks ago, Matt Groves, my first podcast guest, asked for some volunteers to contribute to his excellent brief bio series.

I jumped at the chance to contribute. I find the history of our industry fascinating and while Matt had already covered one of my favorites, I was more than happy to grab the next name in the list and set out to work.

I read a lot of information and I learned a lot in the process. In the end, I had a lot of trouble even coming close to living up to the Brief label. My subject had done a lot to move computing forward. In the end, I was able to cut enough and still maintain a narrative that made sense and kept the importance of Mr. Mauchly. So, if you would, please go over to Matt’s blog and check out my guest post Brief Bio: John W. Mauchly.

Podcasts

Podcast Episode 20 – Russell Patterson on Simple Lookups, NuGet, and Coding in Public

Russell PattersonEpisode 20 brings us another interview podcast and this time I’m talking with Russell Patterson. Russell is the author of Simple Lookups, a .Net library for dynamically handling CRUD operations for your “type” classes.

Along the way, we talk about Simple Lookups, what it was like to make a NuGet package, decisions you make when you know that people you don’t know will read your code, and how he got to where he is today.

Links Mentioned in this Show:

Russell on Twitter and his blog
Simple Lookups on NuGet
Hotel WiFi Test
Code School
Building Cloud Apps with Microsoft Azure
ReviewCast

You can also subscribe to the podcast at any of these places:
iTunes Link RSS Feed

Thanks to all the people who listen, and a special thanks to those who have rated me. I really appreciate it.

The episodes have been archived. Click Here to see the archive page.

Intro to Swift

Swift – Our First iOS Application

Apple's Swift LanguageLast time, we looked at creating functions in Swift. This time, we are going to stop being theoretical and playing in the playground and make an honest to goodness iOS application.

We won’t be getting any billion dollar valuations, but we are going to learn some fundamentals. As I thought about the best way to demonstrate all that there is to see and do when creating an iOS application, it occurred to me that a screencast was the best way to go. I hadn’t ever done one before, but why let that stop me? So, I got Camtasia for Mac, watched some tutorials, and hit record.

It is recorded in 720p HD, so you should change the quality on the video if you want to get the maximum effect. I’d welcome any feedback that you have to give, here or on the YouTube page itself.

Next time – now that we are Swift Veterans (for truth?) – I’m planning on preparing another screencast to make a more complicated iOS application that reads in a RESTful API, displays data, and allows us to interact with it.