Home > .Net, C# > Deep copy against shallow copy in .Net C# dealing with mutable Structs

Deep copy against shallow copy in .Net C# dealing with mutable Structs

In this post I won’t explain the difference between deep copy and shallow copy, what is reference type and Value type – there are plenty stuff about this in the web. I want to share with you some problematic behavior/bug that we found out in application as a result of luck of understanding in current materials.
This issue can be very tricky and hard to debug in runtime, so we need to be wide-awake.

For example you have very simple struct like follows (holds array of points which describes polygon):

public struct MyPolygon
{
	Point[] points;
}

As we all know any struct it’s value type and allocated at stuck, but as we have member reference type Array Point[] points – the Array allocated on the heap. Structs are copied when they passed as argument or as return value. As a result of such behavior reference of our points array was copied as well – which mean that any manipulation with this reference will affect all the copies.
See following GetPolygon(MyPolygon polygon) method – it just returning data member m_localPolygon, but we need to be very careful this data member is Value type which holds mutable reference type array of points.

Public MyPolygon  GetPolygon(MyPolygon polygon)
{
	return m_localPolygon;
}

We have serious bug that doesn’t occurred every application run. The reason that bug occurred was modification of m_localPolygon by another thread, so the returned MyPolygon struct have always updated it’s array of point. Such behavior wasn’t desirable by application design.

The solution was to make deep copy when passing the struct.

public MyPolygon  GetPolygon(MyPolygon polygon)
{
       //using static method for copying one MyPolygon to another
	MyPolygon resultPolygon = MyPolygon.DeepCopyFrom(m_localPolygon);
	return resultPolygon;
}

I have read number of articles where advice is make structs immutable and not to try changing them in run time. Even some people called it “mutable structs are evil “. This is good approach, but not always answering our needs.
Thanks for your attention, hope you will avoid such situations when writing your code.

Categories: .Net, C# Tags: ,
  1. No comments yet.
  1. No trackbacks yet.