I’m working on a small 2D terrain generator and I have an Eater class that I use to remove walls in the generation of my terrain. It is a nested class inside my main Game1 class, and I want to access variables such as mapSize from the Game1 class in my Eater class. I would like to do this so that I can ensure that my Eater does not attempt to remove a wall that is not within the tilemap. How would I go about accessing this private field? I am unable to do it directly. Would I add a constructor that takes a Game1 in my Eater class to access these fields?
Would I add a constructor that takes a Game1 in my Eater class to access these fields?
Yes, that would work.
BUT most people don’t like using nested classes (and IMHO rightfully so…)
Two separate classes with proper interfaces is way to go 🙂
Easiest solution would be to change visibility for the Eater property from private to internal. That way you would not expose it outside of the assembly, but easily be able to access it. Another approach could be a readonly property (public or internal), but that depends on the actual implementation and usage.
No, take a look at the access modifiers to get a better explanation of what private does to the members of a class, struct.
I would recommend you to pass that private field as parameter to a method or constructor in the other class not the whole Game1 class. Also I would recommend you to move your nested class to another file so it is clear it is a separate logic from your main Game1 class
No, take a look at the access modifiers…
I am pretty sure you can modify private members from nested class, but it’s not a good idea…