Simple Question: Reference vs. Value
So, I've got a class called Soldier, and I'm trying to create a seperate copy of it basically. But since classes assign through reference, whenever I create a new soldier, and set it as the old one, they both point to the same instance. I'm wondering if there's anyway to just, copy all of the values over into a new Soldier class.
John BridlePosted May 29, 2008, 4:40 AM
John BridlePosted May 29, 2008, 4:10 AM
public class MyClonableClass:ICloneable
{
private string _test;
public string Test
{
get { return _test; }
set { _test = value; }
}
#region ICloneable Members
public object Clone()
{
MyClonableClass clone = new MyClonableClass();
PropertyInfo[] props = this.GetType().GetProperties();
if (props != null)
{
PropertyInfo copyProp;
foreach (PropertyInfo prop in props)
{
if (prop.CanRead && prop.CanWrite)
{
copyProp = clone.GetType().GetProperty(prop.Name);
copyProp.SetValue(clone, prop.GetValue(this, null), null);
}
}
}
return clone;
}
#endregion
}
this can then be used like this:
MyClonableClass original = new MyClonableClass();
original.Test = "Test";
MyClonableClass copy = new MyClonableClass();
copy = original.Clone() as MyClonableClass;
original.Test = "Not Clone";
Debug.WriteLine(copy.Test);
The debug print out should still read "Test"; hope this helps?