Skip to content

Simple Question: Reference vs. Value

Henry

Asked May 28, 2008, 9:55 PM EDT2 answers
Share
LinkedInX
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.

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    You could implement the IClonable interface and generate some generic reflective code similar to below:

        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?
    0
  • 0
    Ok; just noticed in my Framework guidelines that microsoft recommend creating a Clone method without implementing the Iclonable interface to avoid the confusion between deep and shallow clones. (doh Bill)
    0