C# / XNA: Passing Class instances (objects)

So, not being an expert I was trying to find improved ways of managing external class member access  without resorting to “public static” and ideally wanted an object orientated method, a while ago we were told by Rob Miles how classes or specifically instances of classes (objects) are passed by reference. I understood this however I didn’t really join the dots together for one useful implication it has::

Passing objects as parameters allows the receiving Method and potentially it’s Class, access to the objects members directly. (since its a memory reference to that object, not a copy).

It maybe obvious to some but ultimately,  it means you don’t need to keep feeding objects in as parameters for update methods to show changes, you can just do it once and store it there as a class member. The objects members will all be directly accessible from within that class, even if they are changed elsewhere in your program/game.

I think the thing that didn’t make this obvious to me is the fact that if you pass a class instance member variable instead of the instance itself, this behaviour doesn’t work, you just end up with a copy of the member variable at the point of being passed, but that’s because it’s been passed by value, not reference. Additionally, I found myself repeatedly passing object instances into Update methods, which worked but simply wasn’t needed since a ref could just be passed once and stored for the class. In the context of “Sweepy Cleaner” our Uni course work project, the below highly contrived examples highlight what I mean:

Pass by value Example:

Pass by Reference Example:

The other obvious good thing about passing the class instances instead of specific member variables is that you can of course access all members of that class instead of just the ones you pass. Additionally, it gets around the need to use public static for easy but rather lazy access of class members from outside the class, because only the classes you pass the instance to will be able to access it’s public members, and if you combine with “accessor”/”getter” methods I guess they don’t even need to be public.

(I’ve heard bad things about getter/setters too because it goes against the object orientated nature of C# apparently, but I’m not too bothered about that at this stage).

Anyway, you can of course still pass individual members via the “ref” keyword in the parameter and arguments to achieve the same thing as above but just for a member. I personally think for XNA passing the instance just seems a sound way of doing things. I’m not sure if there are repercussions to doing it like that, but so far it seems sound and hope this may help others who also hadn’t realised its usefulness.

Advertisements