Home > Net >  Beginner: How to properly update references in several classes?
Beginner: How to properly update references in several classes?

Time:05-04

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.

CodePudding user response:

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

  • Related