Posted by: Cirilo Meggiolaro | 03/24/2009

Tip of the day #161 – Getting method and class names with Reflection

Imagine you have a method and from inside this method you want to log some information and the method name must be added to this log. You don’t want to hardcode the method’s name. So, let’s ask some help to the Reflection namespace.

How to…

The MethodBase class available under the System.Reflection namespace provides a nice set of properties and methods that help you achieve this goal. For this example we are going to use the static GetCurrentMethod() method to retrieve a MethodBase instance and then poll this object for the information we need.

To make it easier to follow let’s use the class and method below:

namespace MyXnaGame
    public class Sprite
        public void Draw()
        { }

  • To retrieve the method name: MethodBase.GetCurrentMethod().Name // Output: Draw
  • To retrieve the class name: MethodBase.GetCurrentMethod().DeclaringType.Name // Output: Sprite
  • To retrieve the namespace: MethodBase.GetCurrentMethod().DeclaringType.Namespace // Output: MyXnaGame
  • To retrieve the namespace and class name separated by a dot: MethodBase.GetCurrentMethod().DeclaringType.FullName // Output: MyXnaGame.Sprite

Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s


%d bloggers like this: