I've tried to write a function that clone object, altrougth they do not derive from the ICloneable
interface. For this I copy the part of the memory where the object is stored. That works fine for structs and classes with the [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
prefix. My problem is that it should also work for all other "normal" classes. Is there a way to determine the size of a class?
Here is my clone function:
public static object ForcedClone(this object obj)
{
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(obj));
Marshal.StructureToPtr(obj, ptr, false);
return Marshal.PtrToStructure(ptr, obj.GetType());
}
Here is my test program:
private void Form1_Load(object sender, EventArgs e)
{
Person person = new Person();
person.Age = 23;
person.Male = false;
person.Name = "Jane";
Person person2 = (Person)person.ForcedClone(); // works fine
Person2 person3 = new Person2();
person3.Age = 23;
person3.Male = false;
person3.Name = "Jane";
Person2 person4 = (Person2)person3.ForcedClone(); // don't work
Point point = new Point();
point.x = 13;
point.y = 29;
Point point2 = (Point)point.ForcedClone(); // works fine
}
Here are my test classes:
public struct Point
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class Person
{
public string Name = "John";
public int Age = 15;
public bool Male = true;
}
public class Person2
{
public string Name = "John";
public int Age = 15;
public bool Male = true;
}
Thanks for help!