Passing a Method as a Parameter

I have been working through a few tutorials so as to further my knowledge of 3D programming. In these instances, I’ve been learning about how to do 3D in XNA. While learning about quaternions and matrices, I came across a problem that I have encountered many times before; what do you do if you have a method you need to call from inside a class that uses several objects from the main method?

The usual method either involves using a static instance of the class/method, or making multiple copies of the method and passing the several objects through as part of a long list of parameters. Both of these are some what inefficient/not great coding, so when this issue arose today I decided to investigate alternatives.

To give some context to this post, I have a collision method that exists/existed in the main method of the game which multiple objects were using to calculate if they had collided with any/all of the objects in the game. I couldn’t put this in one of the two classes which call it, as this would mean that the method lost visibility to the objects it needed unless I passed an obscene number of parameters, nor could I make it static, as again it would have been referring to non static objects.

The usual method for accessing anything in the main method from inside a class is to pass the object as a parameter, so I concluded that logically you should be able to pass a method as a parameter. At this point I did some research and discovered that not only was it possible, but that it could be accomplished in a very similar way to the solution in my previous post Anonymous Functions, Func and .Where. Essentially, in the parameters of a method you can define that you want function/method which takes in x and returns y.

 Func<string, int> ConvertStringToInt

Adding this to the parameters allows access from inside the method, meaning that for checking collision I could have:

 public void UpdateObject(Func<Rectanglef, bool> CheckCollision)
        {
            if (!CheckCollision(Position))
            {
                Position = Vector3.Zero;
            }

        }

This passes the “Position” back to “CheckCollision” in the main method and returns a bool. This saves me from having to use the multi-parameter method outlined above and means I, and now you, will be able to use methods from anywhere.

Happy coding,

Adam

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Powered by WordPress.com.

Up ↑

%d bloggers like this: