less than 1 minute read

My jot-down note for whatever I learn while writing some C# code.

Cloning a object

Thu. 8/12/2022

I wrote a component test (a kind of unit test that test the whole process, for example, by calling an API endpoint). It checks if an object is stripped off sensitive data like card number before it’s saved while still retaining them right before being saved. I wrote a test double, so that I can retrieve the object that’s passed as argument. But the test failed saying the object doesn’t contain the card number even though it was before it’s saved. Why? It’s because in C#, a custom object is a reference type and when the property of the object is changed later, it changes the value of the property you reference with different variable names.

The solution is to have a copy of the object by cloning it. Shallow copy of Memberwise() wouldn’t work as it’s shallow copy and would share the objects in the sub-level.

The simplest was to clone an object is serialize and the object and deserialize it.

public static T Clone<T>(this T applicationBase) =>
        JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(applicationBase));

Tags:

Updated:

Comments