Assuming I Have a List<SomeClass> myList; in my Game1-class. It also contains an object of SomeOtherClass otherClass;. How would I modify myList (Add/Remove) out of the otherClass's logic? Or in other words how to get access to the Game1-instance in this situation?

  • \$\begingroup\$ I consider this a XNA specific question as the Game1-Class might have some methods/functions, other C#-classes do not. \$\endgroup\$ – チーズパン Jun 30 '14 at 5:58

2 ways.

  1. Pass Game1 as a parameter to SomeOtherClass and store it as a reference. This will allow you to modify the list by going parentGame.myList.Add(SomeClass);. This requires myList to be public. Alternatively, use wrapper methods around myList (eg parentGame.AddToList(SomeClass);)
  2. Declare myList as public static, then you can go Game1.myList.Add(SomeClass);.

However, I don't recommend 2, as it goes against what statics are meant to be used for. 1 is probably the safer way to go, and more convenient and coder friendly (not to mention safer). Statics can be hard to remove later on down the line.

  • \$\begingroup\$ I understand that solution 2 is no good. I already thought of souluion 1. I also know it works. Still I wonder, is this the "cleanest solution" one can think of? Also, I always thought parameters are passed by value in C# not by reference. Or did you mean I would have to pass them by reference explicitly? \$\endgroup\$ – チーズパン Jun 23 '14 at 12:32
  • 1
    \$\begingroup\$ In C#, reference types (those declared as "class T") are passed by reference. Value types (those declared as "struct T") are passed by value. The "ref" and "out" keywords can modify this behavior. \$\endgroup\$ – user1430 Jun 23 '14 at 15:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.