Is it advisable to use MethodBase to find the method names for logging purposes?

I have the following code in almost every function in my source code.

string methodName = MethodBase.GetCurrentMethod().Name;

My question is

Is it recommended to use the above code to achieve the same considering that reflection is a costly affair?

This is used only for logging purposes.

Jon Skeet
people
quotationmark

No, I wouldn't do this everywhere in your source code.

Firstly, I'd use a dedicated logging package which may have cunning ways of doing a better job, and will certainly be less obtrusive in your source code. There are various options available (log4net, nlog etc). Just how important is the method name anyway? I usually find that if I'm logging with enough context in the message, I don't need to know the exact method name. That's more important for exceptions.

Secondly, if you're using C# 5 you can use CallerMemberNameAttribute to get the compiler to specify the name of the method calling a logging function for you. This is obviously much more sensible than doing it at execution time.

people

See more on this question at Stackoverflow