This happens because the classes are reference types .
There are several ways to solve it
Implement cloning
public class RequestMeetingRoom
{
public RequestMeetingRoom Clone()
{
return (RequestMeetingRoom)this.MemberwiseClone();
}
}
This will create a shallow copy or shallow copy I think that in your case is enough.
Although there is an interface called ICloneable there has been a lot of discussion must use or not. Read link . In any case, to use the MemberwiseClone()
method, it is not necessary to implement it for what is left to your decision.
Use reflection
Using reflection you can copy all the values of the object and copy in depth the values that are by reference. This can be complicated and always depends on the type of object you have since the values can be quite complex.
public class RequestMeetingRoom
{
public RequestMeetingRoom Clone()
{
var t = new RequestMeetingRoom();
var type = t.GetType();
foreach (var prop in type.GetProperties())
{
var p = type.GetProperty(prop.Name);
p.SetValue(t, p.GetValue(this));
}
return t;
}
}
This also creates a shallow copy (and only copies properties) but it's just to illustrate the point. Check out link
Serialization
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
[Serializable]
public class RequestMeetingRoom
{
public RequestMeetingRoom Clone()
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, this);
stream.Seek(0, SeekOrigin.Begin);
return (RequestMeetingRoom)formatter.Deserialize(stream);
}
}
}
This has the disadvantage that you must use the referenced namespaces:
System.Runtime.Serialization
System.Runtime.Serialization.Formatters.Binary
System.IO
You must also mark your class as serializable and all instances of classes that contain your object must also be serializable so that it can work.
Use Automapper
Mapper.CreateMap<RequestMeetingRoom, RequestMeetingRoom>();
Mapper.Map<RequestMeetingRoom, RequestMeetingRoom>(copiaReq , req);
This is usually the simplest since the library is robust and handles all the heavy lifting.