There are two kinds of copying objects.
- reference copy
- value copy
to copy an object by reference you can just use '=' operator.
e.g:
var o1 = new ClassClass();
var o2 = o1;
to copying an object by value, there are several ways, such as:
Copy by a constructor (as you wrote)
public class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Student(Student std)
{
FirstName = std.FirstName;
LastName = std.LastName;
}
}
Make a helper class an pass the s1 as input and return s2 as
result
static void Main(string[] args)
{
var s1 = new Student();
var s2 = ClassHelper.CopyObject(s1);
}
public static class ClassHelper
{
public static Student CopyObject(Student std)
{
var newStudent = new Student()
{
FirstName = std.FirstName,
LastName = std.LastName
};
return newStudent;
}
}
Generic Copy Objects (using Refelection)
private static void CopyClass<T>(T copyFrom, T copyTo, bool copyChildren)
{
if (copyFrom == null || copyTo == null)
throw new Exception("Must not specify null parameters");
var properties = copyFrom.GetType().GetProperties();
foreach (var p in properties.Where(prop => prop.CanRead && prop.CanWrite))
{
if (p.PropertyType.IsClass && p.PropertyType != typeof(string))
{
if (!copyChildren) continue;
var destinationClass = Activator.CreateInstance(p.PropertyType);
object copyValue = p.GetValue(copyFrom);
CopyClass(copyValue, destinationClass, copyChildren);
p.SetValue(copyTo, destinationClass);
}
else
{
object copyValue = p.GetValue(copyFrom);
p.SetValue(copyTo, copyValue);
}
}
}
Write an extension method for this class and I recommended to do this.
public static class ExtensionClass
{
public static Student CopyAsNewObject(this Student std)
{
var newStudent = new Student()
{
FirstName = std.FirstName,
LastName = std.LastName
};
return newStudent;
}
}
static void Main(string[] args)
{
var s1 = new Student();
var s2 = s1.CopyAsNewObject();
}