0

Hi!
I want to make a copy of an class, in this case: Model(XNA).
The problem is that when I edit one of my Models all of the other models of the same type gets changed as well. I can't seem to figure it out.
Xna's official site is down for another couple of days, so therefore the post this here.

Thanks!

(I posted again as it seems like my last post wasn't posted :P)

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by Momerath
2

When using the built in Copy method, it does what is called a shallow copy. This means that anything inside the object that is a reference, they just copy the reference (they don't create a new object of that type).

You'll have to create your own copy method that does a deep copy. If the object is Serializable then you can use this extension method:

public static T DeepCopy<T>(T obj) {
    object result = null;

    using (var ms = new MemoryStream()) {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(ms, obj);
        ms.Position = 0;

        result = (T)formatter.Deserialize(ms);
        ms.Close();
    }

    return (T)result;
}

This, of course, will only copy those parts of the object that are themselves serializable.

Votes + Comments
Nice way to do a deep copy!
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.