I have the following method in an Universe class:
public IWorld CreateWorld(string name) {
//Validations and stuff...
IWorld world = new World(name);
worlds.Add(name, world);
return world;
}
A new World instance is created, and added to a Dictionary<string, IWorld>. Then, I proceed to return the same reference that was added to the dictionary.
All good so far.
In the same Universe class, I also have the following method:
public void DestroyWorld(string name) {
//Validations and stuff...
IWorld world = worlds[name];
worlds.Remove(name);
world.Dispose();
world = null; // <- Setting the object to null
}
Here I am taking the object reference from the dictionary, disposing it and then setting it to null.
Outside this project, I have my Main class:
public static void Main(strig[] args) {
IWorld world = Universe.Instance.CreateWorld("Solarius");
Console.WriteLine(world.Age); //Prints out the world's age
Universe.Instance.DestroyWorld(world.Name);
Console.WriteLine(world.Age); //NullPointerException not being thrown! Prints out the same world's age
}
Why is this happening? Why am I able to call world.Age, if I set the reference to null in Universe.DestroyWorld method?
Isn't the reference stored on the dictionary the same one I am manipulating in the Main class?
IWorldinterface:int Age { get; }IWorld, but I really need a string, since its the key for the dictionary