C# reflexion, cloning

Posted by Enriquev on Stack Overflow See other posts from Stack Overflow or by Enriquev
Published on 2010-04-14T17:31:23Z Indexed on 2010/04/14 17:33 UTC
Read the original article Hit count: 380

Filed under:
|
|

Say I have this class Myclass that contains this method:

 public class MyClass
    {
        public int MyProperty { get; set; }

        public int MySecondProperty { get; set; }

        public MyOtherClass subClass { get; set; }

        public object clone<T>(object original, T emptyObj)
        {

            FieldInfo[] fis = this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);


            object tempMyClass = Activator.CreateInstance(typeof(T));


            foreach (FieldInfo fi in fis)
            {
                if (fi.FieldType.Namespace != original.GetType().Namespace)
                    fi.SetValue(tempMyClass, fi.GetValue(original));
                else
                    fi.SetValue(tempMyClass, this.clone(fi.GetValue(original), fi.GetValue(original)));
            }

            return tempMyClass;
        }
}

Then this class:

public class MyOtherClass 
{
    public int MyProperty777 { get; set; }
}

when I do this:

MyClass a = new MyClass { 
                        MyProperty = 1, 
                        MySecondProperty = 2, 
                        subClass = new MyOtherClass() { MyProperty777 = -1 } 
                        };
            MyClass b = a.clone(a, a) as MyClass;

how come on the second call to clone, T is of type object and not of type MyOtherClass

© Stack Overflow or respective owner

Related posts about c#

Related posts about reflection