copying class in c sharp

I created a variable character, holding the class characters, and then I made it equal to an element in an array of characters called playerdatabase, and then I want to modify characters in runtime without affecting playerdatabase. however, whenever I change values in character, it affect the value I copied from back in playerdatabase. I’m guessing that character was made an reference to the element of playerdatabase instead of having separate values, how do I make character a copy instead of a reference of the element in playerdatabase?

public characters character;
character = mechanics.playerdatabase[controlscript.activeParty[partyIndex]];

I think you can use MemberwiseClone

Otherwise, create a new object and step through and copy the contents into the new object.

still only gave me a shallow copy (a reference to the original object.) I’m still looking for ways to do a deep copy.

C# doesn’t provide copy constructors so you’d have to write one yourself.

I figured, I tried a method I found on google, this:

public static T DeepClone<T>(T obj)
{
 using (var ms = new MemoryStream())
 {
   var formatter = new BinaryFormatter();
   formatter.Serialize(ms, obj);
   ms.Position = 0;

   return (T) formatter.Deserialize(ms);
 }
}

but I couldn’t find MemoryStream or BinaryFormatter. can anyone post a method I could use to create a hard copy of a object?
edit : nvm, found memorystream and binaryformatter but still doesn’t work because everything has to be marked as serilizable.
edit2: solved it, I only hard copied the part that needs to be hard copied and everything else was shallow copied.

Why don’t you just implement a Constructor for that?

public MyClass(MyClass other)
{
    this.a = other.a;
    this.b = other.b;
    (...)
}

MyClass copy = new MyClass(source);

Reflection could work as well, but that would be an overkill I would say.

wouldn’t that just return another shallow copy?
:isconfused:

Take a look at this Scenerio:

public class MyClass 
{
    int a = 0;
    MyClass parent = null;

    public MyClass(MyClass other)
    {
        //Gets Copied
        this.a = other.a;
        //Reference Gets Copied
        this.parent = other.parent;
    }
}

If you want to create new Instances of References of your Source class you would have to do:

public MyClass(MyClass other)
{
    this.a = a;
    if(other.parent != null)
        this.parent = new MyClass(other.parent);
}

I would recommend you to implement such copy-constructors, I wouldn’t use Reflection where you can avoid it.