As per my understanding in C#, when an object is assigned to another object of same type, its reference is copied instead of the value. So I would like to know how to assign an object to another object such that its values are copied and not referenced to the second object..
Asked
Active
Viewed 1.1k times
2 Answers
5
You can see that test2.ErrorDetail is changed to "DTL2", while test1.ErrorDetail remains "DTL1".
public class TestClone : ICloneable
{
public bool IsSuccess { get; set; }
public string ErrorCode { get; set; }
public string ErrorDetail { get; set; }
public object Clone()
{
return this.MemberwiseClone();
}
}
static void Main(string[] args)
{
var test1 = new TestClone() { IsSuccess = true, ErrorCode = "0", ErrorDetail = "DTL1" };
var test2 = (TestClone) test1.Clone();
test2.ErrorDetail = "DTL2";
}

Ray Krungkaew
- 6,652
- 1
- 17
- 28
-
3Uber. However it is unclear if OP wants _deep cloning_, something not mentioned in your answer – Dec 14 '17 at 05:09
-
1FYI MemberwiseClone() is used for ShallowCopy and NOT deep copy, to understand deep and shallow copy in C# this is good article - https://www.geeksforgeeks.org/shallow-copy-and-deep-copy-in-c-sharp/ – Taha Ali Oct 21 '21 at 11:04
0
You have to clone an object instead of assigning a reference.

Mayur
- 33
- 5
-
Ok..thanks for your quick reply..Can you tell me how to perform clone instead of the assignment obj2 = obj1; – Partha Dec 14 '17 at 04:59
-
There are number of examples on the internet. You can check this url: http://www.c-sharpcorner.com/article/cloning-objects-in-net-framework/ – Mayur Dec 14 '17 at 05:03
-
2