Daily C# - (#4) – Multiple References to the Same Object

in #csharp6 years ago

If you assign a variable that points to a reference type to another variable of the same type, both variables end up pointing to the same object in memory. This means that changing the contents of the object through the first reference results in changes that are also seen by the second reference.

The following code:

Person p1 = new Person("Sean", 46);     // New Person object
Person p2 = p1;                         // Points to same object

Results in this situation:

Also, if we change one of the properties of the Person object using the p2 reference, we see the same change when using p1. This confirms that both variables are pointing to the same object.

p2.Age = 50;
int age = p1.Age;       // Also now = 50

Till next time :)

Sort:  

Congratulations @darko-l! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

Award for the number of comments

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

SteemitBoard - Witness Update

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @darko-l! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You received more than 50 upvotes. Your next target is to reach 100 upvotes.

Click here to view your Board of Honor
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

Trick or Treat - Publish your scariest halloween story and win a new badge
SteemitBoard notifications improved

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @darko-l! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Do not miss the last post from @steemitboard:

Are you a DrugWars early adopter? Benvenuto in famiglia!
Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Congratulations @darko-l! You received a personal award!

Happy Steem Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Do not miss the last post from @steemitboard:

Downvote challenge - Add up to 3 funny badges to your board
Vote for @Steemitboard as a witness to get one more award and increased upvotes!