0
\$\begingroup\$

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?

\$\endgroup\$

closed as off-topic by Trevor Powell, Anko, bummzack, MichaelHouse Jun 25 '14 at 16:17

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Programming questions that aren't specific to game development are off-topic here, but can be asked on Stack Overflow. A good rule of thumb is to ask yourself "would a professional game developer give me a better/different/more specific answer to this question than other programmers?"" – Trevor Powell, Anko, bummzack, MichaelHouse
If this question can be reworded to fit the rules in the help center, please edit the question.

  • \$\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
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\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\$ – Josh Jun 23 '14 at 15:05

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