Reputation: 3123
I have a object named post
and I declare a new variable named newPost
as type post
object and then
var newPost = post
but when I Modify any properties of post
object, that Modified Influences properties of newPost
object.
How do I solve this problem?
Upvotes: 1
Views: 7622
Reputation: 2895
You need to provide some way to clone the object. As other commenter said, you are just referencing the same object. See this StackOverflow Question (first answer) for details Deep cloning objects
Upvotes: 1
Reputation: 8936
What you need to do is one of a number of possible things. Here are a couple for consideration.
var
newPost = post.Clone();
var newPost = new
Post(post);
One gotcha to look out for, you probably will want to do what's known as a deep clone or deep copy of the object, so that if your class has any object properties the two instances aren't pointing to the same reference for their properties.
Upvotes: 5
Reputation: 40160
This is an extremely basic question, and I can't write a book on it...
But that's exactly how it is supposed to work. You are setting 'reference' variables; newPost
and post
both refer to the exact same object which is a class
and therefore a Reference type, so you should expect that all changes to one also affect the other.
It sounds like you need to pick up a good basic .NET programming book, and pay particular attention to the differences between Value and Reference types.
The 'solution' is to create a new object and set/copy the individual members of the old object to the new one, but I fear that solution will not serve you too long before you dig some more into things.
Upvotes: 0