How many times have you written Trace code and used MethodBase.GetCurrentMethod() or the Exception.TargetSite or the StackTrace in that code to get the method name or better yet, tried to get the line number. Well, they’ve made that much easier in .Net 4.5. Here is a snippet that shows how easy it is (or will be once it’s released):
public void CallMyMethod() { TraceMessage("This is the trace message I want to see."); } public void TraceMessage(string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { Trace.WriteLine("message: " + message); Trace.WriteLine("member name: " + memberName); Trace.WriteLine("source file path: " + sourceFilePath); Trace.WriteLine("source line number: " + sourceLineNumber); }
Very soon, it will be a breeze!
Happy Coding!