Create a copy of an object using reflection

Ndebata
Posted by Ndebata under C# category on | Points: 40 | Views : 2654

public class ClassA
{
public ClassA()
{
ronly = 300;
}
private static int Count;
public int ID { get; set; }
public string Name { get; set; }
public double Amount { get; set; }
public DateTime DOB { get; set; }
public readonly int ronly;
private int _Age;
public void SetAge(int age)
{
this._Age = age;
Count = age;
}
public int GetAge()
{
return _Age;
}
}
}

Create copy method description

public static ClassA CreateCopy(ClassA src)
{
ClassA obj = new ClassA { };
foreach (var item in src.GetType().GetFields(BindingFlags.NonPublic|BindingFlags.Instance))
{
obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(n => n.Name == item.Name).SetValue(obj, item.GetValue(src));
}
return obj;
}

Comments or Responses

Login to post response