0
0
C Sharp (C#)programming~20 mins

Reference assignment and shared state in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Reference assignment and shared state
📖 Scenario: Imagine you have a simple program that keeps track of a person's name and age using a class. You want to see what happens when you assign one object to another variable and then change the data.
🎯 Goal: You will create a Person class, make two variables that refer to the same object, change the data through one variable, and see how it affects the other.
📋 What You'll Learn
Create a class called Person with two public fields: Name (string) and Age (int).
Create an object of Person with specific values.
Assign this object to another variable to share the reference.
Change the Age using the second variable.
Print the Name and Age from both variables to show shared state.
💡 Why This Matters
🌍 Real World
Understanding reference assignment helps avoid bugs when multiple parts of a program share and modify the same data.
💼 Career
Many programming jobs require knowledge of how objects and references work to write correct and efficient code.
Progress0 / 4 steps
1
Create the Person class and first object
Create a class called Person with public fields Name (string) and Age (int). Then create a variable person1 of type Person and set Name to "Alice" and Age to 30.
C Sharp (C#)
Need a hint?

Define the class with public fields. Then create an object and set its fields.

2
Assign the first object to a second variable
Create a variable person2 and assign it to person1 so both variables refer to the same Person object.
C Sharp (C#)
Need a hint?

Just assign person2 to person1 to share the same object.

3
Change the Age using the second variable
Change the Age field of person2 to 35.
C Sharp (C#)
Need a hint?

Use person2.Age = 35; to change the age.

4
Print the Name and Age from both variables
Print the Name and Age of both person1 and person2 using Console.WriteLine to show that both variables reflect the same data.
C Sharp (C#)
Need a hint?

Use Console.WriteLine with string interpolation to print both variables' fields.