Show all news

How to clone in C#

I was creating some random game in Unity when I encountered the problem that structs won't get serialized by the inspector. So instead of using a struct I started using a class.
!: I want to note that simply replacing struct by class is of course not the right way to go in the first place, but that's for an other discussion.

So I replaced struct by class. The problem now is that it will sometimes copy a reference to other instances of the newly created class in stead of creating a new one.
So the question was, how to simply create new instances of a class? How to clone?

I thought of 3 different ways. There are probably some more but I want to show you the ones I found for now:
!: You can see all the example's in the screenshot provided
Constructor:
The first one is the constructor based cloner. What I simply did here was created a constructer for the new object where you can pass the source to it. In this constructor you can simply copy all the info you need from the source object and put it into the new object.
Example: b = new Coordinate(a);

Clone Function:
The second Cloning type I thought of was using a Clone function. This function must be called on the source object and will return the new object.
Example: b = a.Clone();

Static Create Function:
The last way I thought of was creating a static function on the object on which you can again pass the source object as an parameter
Example: b = Coordinate.Create(a);



What would I do?:
I think this is manly a matter of preference. I don't think one way is actually better than the other.
The only think I can say is that using a static function could be more clean because the cloning code actually happens in a static context.

If you know or find any cool different cloning mechanism don't hesitate to contact me!
Simon
Posted on Wednesday 26 December 2012 02:42:07 by Simon Karman.