For now, let's focus on how to get a very common functionality, but that isn't applied much yet. First, let's see what we can get and how. Next, I will give you some ideas on where to apply it.
You can 2 things to get the current method name. Using reflection:
string MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;Or using the StackFrame:
string MethodName = new StackFrame(0).GetMethod().Name;Cool, now we get the current method name. Now what if we wanted the previous method? Perhaps my method is called from various places and I do not wish to have their name as a parameter.
We can use StackFrame for this:
string MethodName = new StackFrame(1).GetMethod().Name
So, what can we use this for? Let's see some ideas:
- Now our loggers can keep track of the method that's logging the information.
- Gettng the methods (not the name) can help you retrieve the parameters it has received. We will see this in a future post. This information can be excellent when your application is deployed and you are getting an error that you can not reproduce.
- In a certain way, you could limit the methods that can call your method. This seems weird at first, but perhaps some security folks can use this to their advantage.
- Remove all those hardcoded strings!! Or constants at least :)