Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Beginner: How to properly update references in several classes?

In my task, I need to create a linked data structure between classes. A problem I faced is that when declaring references in another class and changing these references later outside the class, the previous class ignores the change. Example:

Location location1 = new Location(); // Name null
World world = new World(location1);
location1 = new Location("entrance"); // Name chosen
Console.WriteLine(location1.Name); // output: "entrance"
Console.WriteLine(world.Start.Name); // output: nothing

class World 
{
 public Location Start {get;set;}
 public World (Location start) {Start = start;}
}

class Location 
{
 public string Name {get;set;}
 public Location (); { }
 public Location (string name) {Name = name;}
}

Looking for a way to update instances so that all references are correctly updated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

location1 = new Location("entrance");

location1 and world.Start are pointing to a memory address. But when the above line is ran, you are telling location1 to point to a different memory address where the new Location is set. world.Start is still pointing to the previous address.

Location location1 = new Location(); // Name null
World world = new World(location1);
location1.Name = "entrance"; // Name chosen

Here, you are actually updating the value of Name, rather than changing where location1 points to.

https://www.tutorialsteacher.com/csharp/csharp-value-type-and-reference-type

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading