1

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?

1

3 Answers 3

5

What you need to do is one of a number of possible things. Here are a couple for consideration.

  1. Implement IClonable and do var newPost = post.Clone();
  2. Have a constructor on the class that has another instance as a paramenter, then copy the properties from the instance passed in to the new instance. i.e. 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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.