| website | https://noelberry.ca |
| exok | https://exok.com |
| website | https://noelberry.ca |
| exok | https://exok.com |
You can create a pattern where child implementations just aren't supposed to do anything until an "OnAdded" is called, but that messes up readonly members and also makes it so they need to "cache" constructor arguments to be used later.
In C++ you could get around this with templates (pseudo code, can't remember syntax)
void Add<T>(constructor params) => children.Add(new T(this, constructor params));
and it wouldn't compile if you mess up the expected parameters. I kind of want that in C#.
I frequently have a design problem in C# where I want to instantiate objects with their data complete, but they also need to reference their owner for ease-of-use. But then the pattern ends up being ugly, like:
UI.Add(new Button(UI, "Confirm"));
Where that first argument is redundant + error-prone.
You can delay the assignment, so the Add method assigns the owner (ex. itemBeingAdded.UI = this) but then the child doesn't have the owner until after its constructor.