C# 5.0 – Caller Information

C# 5.0 has some new features which can aid us in debugging and logging.

Take a look at this code below on how we do logging prior to C# 5.0. Here we have the need of logging the details of the call made to MethodB()

1 class Program 2 { 3 static void Main(string[] args) 4 { 5 InsertToLog("Main"); 6 MethodB(); 7 MethodA(); 8 9 Console.ReadKey(); 10 } 11 12 private static void MethodA() 13 { 14 InsertToLog("MethodA"); 15 MethodB(); 16 } 17 18 private static void MethodB() 19 { 20 } 21 22 private static void InsertToLog(string methodName) 23 { 24 Console.WriteLine("{0} called MethodB at {1} ", methodName, DateTime.Now); 25 } 26 }

In the above code all the methods who call the MethodB() has to make a call to InsertToLog(string methodName). This has 2 major problems.

1) Code repetition

2) Very easily one can miss a call (simply forget to call InsertToLog)

So it would be nice to have the InsertToLog method inside MethodB and if we can pass the caller information to MethodB.

C# 5.0 has this feature. Look at the code below.

1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //InsertToLog("Main"); 6 MethodB(); 7 MethodA(); 8 9 Console.ReadKey(); 10 } 11 12 private static void MethodA() 13 { 14 //InsertToLog("MethodA"); 15 MethodB(); 16 } 17 18 private static void MethodB( 19 [CallerMemberName] string memberName = "", 20 [CallerFilePath] string filepath = "", 21 [CallerLineNumber] int linenumber = 0) 22 { 23 InsertToLog(memberName,filepath,linenumber); 24 } 25 26 private static void InsertToLog(string methodName, string filepath, int linenumber) 27 { 28 Console.WriteLine("{0} called MethodB at {1} from {2} on line number {3}", methodName, DateTime.Now,filepath,linenumber); 29 } 30 }

In order to use the caller information you have add the following reference.

 

using System.Runtime.CompilerServices;

Advertisement