2

I want to define a method to copy data from another data class to a new defined object and then return it. For example:

public GameData Gett() {
    point pt = new point();
    return pt;
}

public class point : GameData
{
    public int TouchGround;
}

So what should I do to copy the data from TouchGround to pt and then return it as an object?

2 Answers 2

1

If your objects basically have some primitive type properties, your data classes like Point (should be uppercase!) could implement the ICloneable interface. That means mapping the data by hand:

class Point : ICloneable
{
    public int TouchGround;

    public object Clone()
    {
        return new Point
        {
            TouchGround = this.TouchGround
        }
    }
}

If you have to copy alot of properties on different classes, you could utilize a framework like automapper (http://automapper.org/). It allows you to do something like:

Mapper.CreateMap<Point, Point>();
var point = new Point();
Mapper.Map<Point, Point>(existingPoint, point);

Another option would be creating your data objects as structs. Structs are copied on assignment. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/structs

Sign up to request clarification or add additional context in comments.

Comments

1

For shallow copy, you can use MemberwiseClone() method available in C# ICloneable interface. So, your point class should be changed to this.

public class point : GameData,  ICloneable
{
    public int TouchGround;

    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

For shallow copy, you can use this.

    point a = new point();
    a.TouchGround = 1;

    // Next lines, create a shallow copy of a and put into b.
    point b = (point)a.Clone();
    b.TouchGround = 20;

    Console.WriteLine(a.TouchGround);
    Console.WriteLine(b.TouchGround);
    Console.ReadLine();

For deep copy, you would need to serialize this class and then de-serialize as another object of same type. You can do this using Newtonsoft.JSON. Your class should be serializable. Check this for similar details. You can also use DataContractSerializer.

    point x = new point();
    x.TouchGround = 35;

    point y = JsonConvert.DeserializeObject<point>(JsonConvert.SerializeObject(x));
    y.TouchGround = 40;

    Console.WriteLine(x.TouchGround);
    Console.WriteLine(y.TouchGround);
    Console.ReadLine();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.