Implement the class Icloneable in its class that will provide you to clone a copy of the class with the same values, but being distinct objects. Within the method created by the implementation Icloneable calling Memberwiseclone() that returns a copy in a new object.
Code:
public class Propriedades: ICloneable
{
public Propriedades()
{
}
public int Id { get; set; } = 1;
public string Name { get; set; } = "Name 1";
public object Clone()
{
return MemberwiseClone();
}
}
Use:
Propriedades p = new Propriedades();
Propriedades c = (Propriedades)p.Clone(); //Clone "ICloneable"
Another way is by using reflection (Reflection):
Propriedades propr1 = new Propriedades();
propr1.Id = 2;
propr1.Name = "Nome 2";
Type propType1 = propr1.GetType();
Propriedades propr2 = new Propriedades();
Type propType2 = propr1.GetType();
foreach(PropertyInfo info in propType1.GetProperties())
{
propType2.GetProperty(info.Name)
.SetValue(propr2, info.GetValue(propr1));
}
the above code can be simplified with extension methods with a code like this:
public static class Utils
{
public static T Clone<T>(this T _t)
where T: class
{
T _r = Activator.CreateInstance<T>();
Type _t1 = _t.GetType();
Type _r1 = _r.GetType();
foreach (System.Reflection.PropertyInfo info in _t1.GetProperties())
{
_r1.GetProperty(info.Name)
.SetValue(_r, info.GetValue(_t));
}
return _r;
}
}
and its use is very similar to the first alternative:
Propriedades propr1 = new Propriedades();
propr1.Id = 2;
propr1.Name = "Nome 2";
Propriedades propr2 = propr1.Clone(); // método de extensão
There’s also a package from nuget the Automapper, example:
Propriedades propr1 = new Propriedades();
propr1.Id = 2;
propr1.Name = "Nome 2";
Mapper.Initialize(cfg => { });
Mapper.Configuration.CompileMappings();
Propriedades propr2 = Mapper.Map<Propriedades>(propr1);
Remarks: i would pass the values to the new instances to have no problem with references and values unexpected. I would only use it if it didn’t compromise the code and its instances, yet the simple assignment mode is the best way to implement.
References:
Do you have control over this class? You can touch it?
– Maniero