class example:
public class Customer
{
public int CustomerID { get; set; }
}
using the class:
Customer customer1 = new Customer();
customer1.CustomerID = 1;
Now how can I create a customer2 class with all the values that are stored in customer1?
You can do it manually:
var customer2 = new Customer { CustomerID = customer1.CustomerID };
You can implement ICloneable
interface in Customer
class:
public class Customer : ICloneable
{
private int CustomerID { get; set; }
public Customer Clone()
{
return new Customer { CustomerID = this.CustomerID };
}
object ICloneable.Clone()
{
return this.Clone();
}
}
and then use it:
var customer2 = customer1.Clone();
You can serialize your object into XML/JSON and then deserialize it into new object, as described in this answer: Deep cloning objects in C#.
Or you can use reflection to get and copy all properties/fields values into your new Customer
instance. It could have bad performance, but you'd have to measure it to make sure how bad it is.
Edit
One more way to do that: you can make reflection version faster using Expression Tree! Get all fields/properties and compile all necessary assignments at runtime using Expression.Lambda
. After that every next Clone
call will use compiled code so there will be no performance drawback at all. I've created Clone<T>
extension method which does exactly that, using Expression
class, static constructor and reflection. You can find the code on CodePlex: CloneExtension.cs
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments