How to access Object containing This, from within This?


Supposing I have a class called Game. Game has a public List<GameObject> called ObjectList. A GameObject in ObjectList wants to create a new GameObject and add that to the ObjectList. How can this be done?

Code Representation of Problem

class Game { public List<GameObject> ObjectList = new List<GameObject>(); public Game() { ObjectList.Add(new GameObject()); } } class GameObject { public GameObject() { //Obviously this won't work ObjectList.Add(new GameObject()); //How do? } } 

Backstory info

When I first learned C-style programming, I was using GameMaker scripting. It was limited compared to languages like C++ and C#, but the framework was incredibly powerful and taught me the concepts of OOP and algorithm design.

I stopped using GameMaker a year or two ago, but I still haven't found such a clean and minimalist 2D framework, and I have a lot of code in GameMaker that cannot be directly ported because of problems like these. Now as a bit of an exercise, I'm working on a small library that implements GameMaker's built-in functions in C# using Monogame, which is already very similar, though smaller.

For the record, I have no intention of using this in any actual game. Most of my work in GameMaker was actually made of simple life simulations, data visualizations, and algorithm demonstrations.

by cadika_orade via /r/csharp

Leave a Reply