C# creating another instance of same class - Reflection? - c#

I'm making a game which involves placing objects in a room. The room stores a list of objects that can be placed in it, e.g.
List<RoomObject> possibleObjects = new List<RoomObject>(){ new Bed(), new Table() };
These objects are then each sent to buttons which allow the user to click the button, entering a placement phase for the chosen object, where the user then clicks in the room, and the object is placed.
e.g.
public Room currentRoom;
public RoomObject currentObject;
//...
public void onClick()
{
if (CanPlace) currentRoom.Add(currentObject);
}
My problem is, if the user wants to place more than one of the same object, the current way it's set up will mean the exact same object will be added to the room, and if that object is later edited in some way (e.g. Bed.occupied = true), it will affect all of the objects of that type in the room.
Is there a way to duplicate an object (to get a separate reference) without me having to use reflection (which I'm not very familiar with, and feel is unsafe code).
I assume the reflection way would be passing around a Type and then having to call constructors using Type.GetConstructor, but I'd rather not do this if possible. If reflection is the only way, could someone provide example code for how to do it?
EDIT - perhaps I need to specify that my variable currentObject will not hold a variable of Type RoomObject, but a subclass such as Bed. (Bed inherits from RoomObject).

You should define a copy constructor for your object. This will allow you to instantiate a class based on values from another instance of that class. Here is a tutorial:
http://msdn.microsoft.com/en-us/library/ms173116(v=vs.80).aspx
public class RoomObject
{
public RoomObject(RoomObject roomObject)
{
//Copy room object properties
}
}
public class Bed : RoomObject
{
public Bed(Bed bed) : base(bed)
{
//Copy Bed properties
}
}
Usage
Bed bedOne = new Bed();
Bed bedTwo = new Bed(bedOne); //Create a bed using Bed copy constructor
RoomObject roomObject = new RoomObject(bedOne) //Creates a room object using RoomObject copy constructor
Further Edit
public abstract class RoomObject<T> where T : new()
{
protected T CreateRoomObjectCopy(T roomObject)
{
T concreteType = new T();
//Copy Room object properties
return concreteType;
}
public abstract T Copy(T roomObject);
}
public class Bed : RoomObject<Bed>
{
public override Bed Copy(Bed roomObject)
{
Bed newBed = CreateRoomObjectCopy(roomObject);
//Copy bed properties
return newBed;
}
}

Either use a Copy Constructor or with reflection.
With reflection it's not as complicated as you imagine, it's a matter of using the Activator class along with the Type and you can obtain an instance of that Type.

There's nothing really unsafe about reflection. It's one of the beauties of managed languages like .NET.
I may be wrong but it sounds like you want to clone an object instance (as opposed to having two references to the same instance).
Take a look at the following links.
Deep cloning objects
How to Clone Objects
Additional:
You could try implementing ICloneable, thus providing a mechanism of your own to clone the object
Exmaple:
public class RoomObject : ICloneable
{
public object Clone()
{
return new RoomObject { X = this.X, Y = this.Y, Z = this.Z };
}
}
RoomObject ro = new RoomObject();
RoomObject ro2 = (RoomObject)ro.Clone();

class Program
{
static void Main(string[] args)
{
Bed bed = RoomObject.RoomName("Bed");
Console.WriteLine(bed.name);
//outline:Bed
Console.Read();
}
}
public class RoomObject
{
public static Bed RoomName(string BedName)
{
Bed newBed = new Bed();
newBed.name = BedName;
return newBed;
}
}
public class Bed
{
public string name { get; set; }
}

Related

feeding a Type into a constructor

class Program{
void Apple(){
List<Banana> apple = new List<Banana> { (new Banana(Cucumber, 5)), (new Banana(Dates, 6)) };
}
}
class Banana{
public Banana(Type eggplant, int feijoa){
new eggplant(feijoa);
}
}
class Cucumber{
public Cucumber(int feijoa){
}
}
class Dates{
public Dates(int feijoa){
}
}
basically it feeds a bunch of information from the program class to the Banana class, which then filters that information and uses it to create instances of a bunch of different classes.
the problem is within the Program class, where even though it registers that a Type is needed to complete the Banana constructor, when given a Type, like Cucumber or Dates, it says giving a type there is not considered valid in the given context, so i would like some help with understanding how to fix it, thanks in advance.
while structuring my program this way might seem weird and inefficient, it's mostly to help simplify viewing and editing the front end of my program.
you should use typeof operator while passing argument to constructor.
Like :
List<Banana> apple = new List<Banana> { (new Banana(typeof(Cucumber), 5)), (new Banana(typeof(Dates), 6)) };
However inside constructor you need to use Activator.CreateInstance(typeof(T), object[] args) to instantiate either Cucumber or Banana objects.
Also you better consider redesigning your class like :
class Banana<T> where T: new(){
public Banana(int feijoa){
Activator.CreateInstance(typeof(T), new object[]{feijoa}
}
so your snippet would be changed to :
List<Banana> apple = new List<Banana> { (new Banana<Cucumber>(5)), (new Banana<Dates>(6)) };
To get the Type instance of Cucumber class you should use typeof(Cucumber). So your constructors should change to look like the following:
new Banana(typeof(Cucumber), 5)
new Banana(typeof(Dates), 6)
UPDATE
Here is some more context regarding your code. The constructor of the Banana type is actually incorrect.
It's not possible to call new on a type instance. What you're actually trying to do is instantiate an object of the passed eggplant parameter. There are multiple ways you can achieve that. But before going into details I recommend you to read about type constructors first.
Besides, it's a bit unclear what your intent is. What you're trying to do with the newly created instance. I would just assume for now that you're going to store that instance in some member variable, as follows:
public class Banana
{
private readonly object instance;
public Banana(Type eggplant, int feijoa)
{
this.instance = Activator.CreateInstancenew eggplant(feijoa, new object [] {feijoa});
}
}
Here I've used the Activator type which will create an instance of a given type if it'll find a matching constructor based on the parameters you've passed. Otherwise, an exception will be thrown.
While the above-mentioned approach would work, it's not ideal as it provides no type safety. So it would be great to use Generics here, but that is not possible with current code because of the requirement of having a constructor, which accepts a parameter. There is still a way to achieve that, but it'll require a lot of code changes, which is not directly related to your question. You can read more about Generics here.
While there are a lot of other options, I would ask whether it's really a requirement to have the design you've got here. Why not pass in the instances to the Banan class directly. To do that, you'll need to make sure there is a base class/interface, which all the potential parameters to the Banana constructor will extend. Here is an example you could go with:
class Program
{
void Apple()
{
List<Banana> apple = new List<Banana> { new Banana(new Cucumber(5)), new Banana(new Dates() { Feijoa = 6 }) };
}
}
class Banana
{
private readonly ICommon instance;
public Banana(ICommon instance)
{
this.instance = instance;
}
}
public interface ICommon
{
int Feijoa { get; set; }
}
class Cucumber : ICommon
{
public Cucumber(int feijoa)
{
this.Feijoa = feijoa;
}
public int Feijoa { get; set; }
}
class Dates : ICommon
{
public Dates()
{
}
public int Feijoa { get; set; }
}
Sorry, the provided context is not enought to be more specific. In the meantime, I tried to share as much as possible. I know, it may look scattered a bit.
Hope this helps.

How do I make T work with intherited classes?

I'm programming a dungeon generator for a roguelike. I've a base class called Room. It contains methods that can be inherited by other types of rooms. It looks like this but then a little more advanced
class Room
{
protected virtual void Construct() { /*make square room here*/ }
}
class RoundRoom : Room
{
protected override void Construct() { /*make round room here*/ }
}
My class that generates rooms needs to be "fed" with rooms to generate. The room handles the construction, and I've different types of rooms. And I want it to have it that certain specific rooms can be generated based on some conditions or chances.
So I feed it with different types of rooms. First I thought of this:
class RoomEntry
{
public Point chance;
public Room room;
}
And then have an array of it
RoomEntry[] entries;
And then just feed it
Generator.Feed(entries[random.Next(0, 10)].room); // just an example
But that won't work! If I edit the room in the generator, It'll change in RoomEntry too! And I need to use it quite a few times!
So if I would make new rooms based on some room type... It'll work!
So I came up with this:
class RoomPlanner
{
class RoomEntry<T> where T : Room, new()
{
public Point chance;
T r;
public Room RoomToBuild()
{
return new T();
}
}
RoomEntry<Room>[] entrys;
public void Foo()
{
entrys = new RoomEntry<Room>[10];
for (int i = 0; i < entrys.Length; i++)
{
entrys[i] = new RoomEntry<RoundRoom>();
}
}
}
But that's not possible. I'm getting this error:
Cannot implicitly convert type 'Super_ForeverAloneInThaDungeon.RoomPlanner.RoomEntry<Super_ForeverAloneInThaDungeon.RoundRoom>' to 'Super_ForeverAloneInThaDungeon.RoomPlanner.RoomEntry<Super_ForeverAloneInThaDungeon.Room>'
So, how do can I make it accept classes that inherit from Room, or how do I take a different approach to this problem?
It's not an duplicate of this. That's a different problem, and I do not have enough information to fix my problem entirely out of it.
The problem is that covariant/contravariant type parameters can only be used with interface or delegate types. (More information on that in this MSDN article.) Essentially, there is no way to declare a RoomEntry<T> that is contravariant with RoomEntry<Room>, even with the constraint that T : room.
You could get around this by defining an IRoomEntry interface that is implemented by RoomEntry<T>, like this:
interface IRoomEntry
{
Room RoomToBuild();
}
class RoomPlanner
{
class RoomEntry<T> : IRoomEntry
where T : Room, new()
{
public Point chance;
T r;
public Room RoomToBuild()
{
return new T();
}
}
IRoomEntry[] entrys;
public void Foo()
{
entrys = new IRoomEntry[10];
for (int i = 0; i < entrys.Length; i++)
{
entrys[i] = new RoomEntry<RoundRoom>();
}
}
}
Seems like you just want to Clone the room before feeding it to the Generator. You could just add a Clone method to your Room class:
Room Clone() { return (Room)this.MemberwiseClone(); }
And then feed it like so:
Generator.Feed(entries[random.Next(0, 10)].room.Clone());

C# Cross-Class object

I'm working on very simple Roguelike game (just for myself) and get a question:
As it is not possible to create a cross-class struct-object (entity in the game case) that could be accessible from any class of my program, what to use to create a cross-class object? I was thinking of something like storing all newly created object (enities) in a static object array, but I guess there is more simple solution on this problem.
Question itself: How to create a cross-class accessible object(s) with your own properties?
Thanks everybody, I found what I was searching for.
It seems like you tried passing around a value type (a struct) between different classes and you noticed that when you update the value in one place it doesn't change the value in another place.
That's the basic difference between value types and reference types.
If you are creating the struct yourself you may want to instead define it as a class.
If not, you could wrap all your structs in a class and pass the class around as your state object.
If all you have is simply a list of the same type of struct (like Points), just pass the List itself around. C# collections are implemented as classes.
public class GameState
{
public Point PlayerLocation { get; set; }
public List<Point> BulletPoints { get; set; }
public double Health { get; set; }
}
Now you can create a GameState and pass it around to different classes:
public class Game
{
private GameState _state = new GameState();
private BulletUpdater _bulletUpdater = new BulletUpdater();
public void Update()
{
_bulletUpdater.UpdatePoints(_state);
// Points have now been modified by another class, even though a Point is a struct.
}
}
public class BulletUpdater
{
public void UpdatePoints(GameState state)
{
for (int i = 0; i < state.BulletPoints.Count; i++)
{
Point p = state.BulletPoints[i];
state.BulletPoints[i] = new Point(p.X + 1, p.Y + 1);
}
}
}
Just remember in the above code if I were to write:
Point p = state.BulletPoints[i];
p.X += 1;
p.Y += 1;
That wouldn't affect the original point! When you read a value type from a list or from a class into only copies the value into a local variable. So in order to reflect your changes in the original object stored inside the reference type you need to overwrite it like so:
state.BulletPoints[i] = p;
This same principal is why the following also will not work:
state.PlayerLocation.X += 5; // Doesn't do anything
state.PlayerLocation.Y += 5; // Also doesn't do anything
The compiler would tell you in this case that you are doing something wrong. You are only modifying the returned value of the property, not the backing field itself. You have to write it like so:
state.PlayerLocation = new Point(state.PlayerLocation.X + 5, state.PlayerLocation.Y + 5); // This works!
You can do the following:
Using IoC Framework, like Ninject. You can setup Ninject to create single instance for all usages.
The other option is to use Singleton pattern design pattern
And the third one is to use static property
It sounds like you want to use the Singleton pattern:
http://en.wikipedia.org/wiki/Singleton_pattern
Here is an example of what this would look like in C#:
public class Singleton
{
static Singleton()
{
Instance = new Singleton();
}
public static Singleton Instance { get; private set; }
}
It's possible. What about public and static class?
public static class CrossClassObject
{
public static object MyProperty { get; set; }
public static void MyMethod() {}
}
Of course this class should be placed in the same namespace that other ones.
How to use it?
class OtherClassInTheSameNamespace
{
private void SomeMethod()
{
var localVariable = CrossClassObject.MyProperty; // get 'cross-class' property MyProperty
CrossClassObject.MyMethod(); // execute 'cross-class' method MyMethod()
}
}
No idea what you are trying to achieve... but if you want a list of objects accessible 'cross-class', just make a static class with a list of objects and then when you reference your class from any other class, you will have access to its list of objects. Here is something like that:
public static class ObjectController
{
private static IList<object> existingObjects;
public static IList<object> ExistingObjects
{
get
{
if (existingObjects == null)
{
existingObjects = new List<object>();
}
}
}
}
public class MyObject
{
public MyObject()
{
ObjectController.ExistingObjects.Add(this);
}
public void Delete()
{
ObjectController.ExistingObjects.Remove(this);
}
}
Then you can add stuff like
MyObject newObj = new MyObject();
//// other stuff... This object should now be visible to whatever other class references ObjectController
newObj.Delete();

C# value/reference passing?

I have a declared entity of a class, and want to assign different pre-made templates to it without the templates ever changing. Using a const doesn't seem to do the trick.
Example:
Weapon w1;
w1 = Sword; // premade weapon.
w1.reducedamage(1); // for example a debuff
In this case the premade weapon's damage would be decreased, and it would no longer be available as a template. This problem becomes more profound with enemies.
Example:
Enemy enemy;
enemy = enemies[r] // r being a randomly generated integer and enemies a list of enemy templates
Fight(player,enemy); // this method would resolve a fight between the two entities of the type Character.
This problem would not be visible in the player class, since player is a single reference being passed along all the game methods - because there is only one player. Every time the player fights, an enemy template would be "corrupted".
How would I create templates or classes/structs in general that always pass by value, meaning that the properties of a first class would have the same values as a second, without any relationship between the two classes?
The only success I've gotten with this is to create a method that manually copies each attribute of every class that has a template onto another entity of the same class; but this is extremely unpractical since it needs constant upgrading whenever a new class is added, or an old one changed.
I must be missing something. This seems like a reasonably simple issue that is easily solved by inheritance, perhaps in conjunction with some sort of Factory. First, you don't want to use a reference to a single instance, you want to create a new instance each time so it is a unique object. I prefer classes over structs, but you could easily create a new struct as well. You could use a Factory to create various pre-configured instances of the objects that have pre-defined values. For example, the Sword of Damocles or the Sword of Destiny.
public static class WeaponFactory
{
public static Weapon CreateSword(SwordType type)
{
var sword = new Sword(); // plain, old default sword
// override properties based on type
switch (type)
{
case SwordType.SwordOfDamocles:
sword.FallTime = GetRandomFutureTime();
break;
case SwordType.SwordOfDestiny:
sword.Invincible = true;
break;
...
}
return sword;
}
...
}
Alternative using Actions
public static class WeaponFactory
{
public static Weapon Create<T>(Action<T> decorator) where T : IWeapon, new()
{
var weapon = new T();
decorator(weapon);
return weapon;
}
public static void SwordOfDamocles(Sword sword)
{
sword.FallTime = GetRandomFallTime();
}
public static void SwordOfDestiny(Sword sword)
{
sword.Invincible = true;
}
}
var weapon = WeaponFactory.Create(WeaponFactory.SwordOfDamocles);
What you want is object cloning. You can implement it via the ICloneable interface[1]. That requires that you implement your own cloning mechanism though--you have to do the heavy lifting.
However, what you probably should do instead is just have the constructor take a parameter that represents the template you want, and then fill the properties of the object in question based on that template. That's the direction I go when I want to make duplicate things with a base set of values.
You could do actual copying (e.g. provide a copy constructor as in http://msdn.microsoft.com/en-us/library/ms173116(v=vs.80).aspx ), but what I've seen most often in such cases is a factory pattern, e.g. Weapon w1 = Weapon.CreateSword(); or Enemy e=Enemy.CreateEnemyOfType(r);
you could build a method to return multiple enemies in either a generic collection or array into your enemy class. Something like:
public shared function getEnemies(num as integer, type as string) as list(of clsEnemy)
dim enemyGroup as list(of clsEnemy)
for i = 0 to num - 1
dim thisEnemy as new clsEnemy(type)
enemyGroup.add(thisEnemy)
next
return enemyGroup
end function
Contrary to copying objects to implement some kind of "applied object" pattern, it's good to keep in mind it's not the sword "base item" that is being altered, but the item your player is carrying.
For example, a given sword, say "rusty old sword", will always have a base damage of 50. Now if someone applies "old stuff gets better magic" to it, it's not the "rusty old sword" that gets more damage: if some other player that hasn't got that kind of magic picks up the item, it's back to its base damage of 50.
So if you implement some kind of EquippedWeapon (or even EquippedItem) class, you can let your player equip weapons and give it extended properties. Something like this to declare a Sword:
interface IWeapon
{
int Damage { get; }
}
class Sword : IWeapon
{
public int Damage { get; private set; }
public Sword()
{
this.Damage = 50;
}
}
Now we have a sword with a base damage of 50. Now to let the player carry this sword:
interface IDamageModifier
{
int Damage { get; set; }
}
class EquippedWeapon : IWeapon
{
public int Damage
{
get
{
return CalculateActualDamage();
}
}
public List<IDamageModifier> DamageModifiers { get; set; }
private IWeapon _baseWeapon = null;
public EquippedWeapon(IWeapon weapon)
{
_baseWeapon = weapon;
}
private int CalulcateActualDamage()
{
int baseDamage = _baseWeapon.Damage;
foreach (var modifier in this.DamageModifiers)
{
baseDamage += modifier.Damage;
}
return baseDamage;
}
}
A weapon contains a list of active modifiers, that affect the damage of the carried item, but not the base item. This way you can share one Sword instance with many (non-)playable characters.
Now if the player gets attacked and that attack has a damage effect, you simply apply that to the item(s) the player is carrying, so each successive attack from that player will have those effects applied:
class Player
{
public EquippedWeapon PrimaryWeapon { get; set; }
public Player()
{
this.PrimaryWeapon = new EquippedWeapon(new Sword());
}
public void UnderAttack(Attack attack)
{
// TODO: implement
if (attack.Buffs...)
{
this.EquippedWeapon.DamageModifiers.Add(attack.Buffs);
}
}
}
I wrote an answer answering your question directly. But now I see that all you want is to create items that are the same but not linked.
That's what happens anyway when you create an instance. You don’t have to do anything.
If you have:
class Class1
{
public int i;
}
Then:
Class1 c1 = new Class1() { i = 1 };
Class1 c2 = new Class1() { i = 2 };
Text = c1.i.ToString();
Prints "1", not "2".
And if you mean you want a "Player" class with sub-classes "Friend" and "Foe" - That's what inheritance is for:
class Player
{
}
class Friend : Player
{
}
class Foe : Player
{
}
EDIT:
Perhaps this will make the task easier: (The "Duplicate" method)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Class1 c1 = new Class1() { i = 1, j = 2 };
Class1 c2 = Duplicate(c1);
c1.i = 3;
Text = c2.i.ToString();//Prints "1";
}
public Class1 Duplicate(Class1 c)//Duplicates all public properties.
{
Class1 result = new Class1();
PropertyInfo[] infos = typeof(Class1).GetProperties();
foreach (PropertyInfo info in infos)
info.SetValue(result, info.GetValue(c, null), null);
return result;
}
}
public class Class1
{
public int i { get; set; }
public int j { get; set; }
}

Why objects are orphan, when creator exist

Consider following code
public class City
{
public string Name { get { return "New York"; } }
Building empEstate;
Building nyTimes;
public void Init()
{
// I hate passing "this" to all object
empEstate = new EmpEstate(this);
setSomeProperty(empEstate);
// any one can create new object of some other city
// and pass to the building
nyTimes = new NYTimes(this);
...
other = new OtherBuildings(this)
}
public void PrintAddresses()
{
empEstate.Print();
nyTimes.Print();
...
other.Print();
}
}
public abstract class Building {
City _city;
public Building(City city){
this._city = city;
}
public abstract string Name { get;}
public void Print(){
Console.WriteLine(this.Name);
Console.Write(",");
Console.WriteLine(this._city.Name);
}
}
First thing I want better solution to this approach. Print is just an example. Actually each building object raise some event to City object. I don't want to add handler to each building as there could be several buildings in city. Also I do not want to add each of them into list, as it is two task for each building (one initialization and second add to list, one forget to add to list when writing new building). For this, I want caller to be automatically available to callee, like Parent property of control (though it was added to this.Controls)
Using memory, can we know who is the parent of current object. How does GC knows that object is not being referenced (including creator). Can't we create a method (safe or unsafe) using memory to identify the caller object. I see we can use StackTrace to see the call hirarchy, can we intercept here when a new object is being created.
Building factory on city solved my problem of passing this to each object
public interface ICity
{
string Name { get; }
}
public abstract class City : ICity
{
public T CreateBuilding<T>()
{
T buildingInstance = Activator.CreateInstance<T>();
((IBuilding)buildingInstance).SetCity(this);
return buildingInstance;
}
public abstract string Name { get; }
}
interface IBuilding
{
ICity City { get; }
void SetCity(ICity city);
}
public abstract class Building : IBuilding
{
private ICity _city;
public ICity City { get { return _city; } }
public void IBuilding.SetCity(ICity city)
{
this._city = city;
}
public abstract string Name { get; }
public void Print()
{
Console.WriteLine(this.Name);
Console.Write(",");
Console.WriteLine(this._city.Name);
}
}
public class EmpEstate : Building
{
public override string Name { get { return "Emp State"; } }
}
public class NYTimes : Building
{
public override string Name { get { return "NY Times"; } }
}
public class NewYorkCity : City
{
public override string Name { get { return "New York"; } }
EmpEstate empEstate;
NYTimes nyTimes;
public void Init()
{
// Now I dont need to pass this
empEstate = this.CreateBuilding<EmpEstate>();
setSomeProperty(empEstate);
// now any one cannot create building in new your and
// say it belongs to Philedelphia :)
nyTimes = this.CreateBuilding<NYTimes>();
}
public void PrintAddresses()
{
empEstate.Print();
nyTimes.Print();
}
}
Problem was there were several classes already created and for new functionality we needed the creator object in the base class of Building Object. We did not wanted to modify the constructor of each class and pass this object to each. And City class (in example) was basically code on plugin side, so allowing them to pass city (if plugin developer pass wrong city) may disturb the functionality of entire app. So modifying the plugin base solved my purpose. Suggestions are welcome.
There is no logical "owner" of an object. Inspecting the stack trace is... not usually ideal. By comparison to Parent, that is not very different to your existing approach - merely that is set via methods/properties rather than in the constructor.
If the city is only necessary for the context of methods like Print, why not pass it in as a parameter, i.e. nyTimes.Print(this) etc. If you might need other values, rather than taking lots of parameters, consider using some kind of context object that has a city - i.e.
class PrintContext {
public City City {get;private set;}
// other stuff...
public PrintContext(City city/*, other stuff...*/) {
City = city;
}
}
I think you are misusing the terms parent and creator. The object that created the instance has no special relationship with the instance (e.g. factories create objects, but do not maintain references to them), so, in general, there is no way to find out who or what created a concrete instance.
In the same sense, parent has no meaning on a general object. We can somehow infer that the Form is parent to the TextBox, but that is not a special relationship. It this case it just means that the TextBox is in the form's Contols collection, and that it's Parent is set to the Form.
You are right that this could potentially lead to inconsistencies (Form1 thinks that TextBox is it's child, but the TextBox thinks that it's Parent is Form2), but I do not know of, and don't think there is a better solution of this kind of relationship than the Children collection / Parent reference.
Picking a few of your many questions:
I hate passing this
Why? You are telling the building which city it belongs to. How else could you do this. I see that as a common idiom for wiring objects together.
Also I do not want to add each of them into list, as it is two task
for each building (one initialization and second add to list, one
forget to add to list when writing new building).
I'm not clear what list you want to add them to, but your concern about "forgetting" is overcome if you do the work in the base constructor:
public Building(City city){
this._city = city;
// add the building to the list here - nothing to "forget"
}
As for GC, once a creator has created something there is no relationship between them unless you choose to retain a reference. You have done that with
empEstate = new EmpEstate(this);
so as long as the City is not a candidate for garbage collectio then the EmpState won't be either.

Categories