Calling Method Information

In the large Applications, it is quite common to apply logging, so that the issues/flow of the applications can be tracked easily. Moreover, important information about the calling source file, method name and the line number from where a method is being called can be very helpful. In order to easily track these things. C# provides different classes, which includes.
  • CallerFilePathAttribute
    It is helpful in getting the name of the file from which the method is being called. 

  • CallerMemberNameAttribute
    It is helpful in tracking the method name in which the current method is being called. 

  • CallerLineNumberAttribute
    It is helpful in tracking the line number on which the current method is being called. 
These classes provide attributes, which can be used as the method parameters and get the file name, the calling method name and line number from which the method is being called. These parameters are required to be specified as the optional parameters.
 
For example, consider the following code snippet.  
  1. class Program  
  2.    {  
  3.        static void Main(string[] args)  
  4.        {  
  5.            MethodA();  
  6.            Console.ReadKey();  
  7.        }  
  8.   
  9.        private static void MethodA([CallerMemberName] string memberName = null, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = 0)  
  10.        {  
  11.            Console.WriteLine("Member is:" + memberName);  
  12.            Console.WriteLine("Path is:" + filePath);  
  13.            Console.WriteLine("Linenumber is:" + lineNumber);  
  14.        }   
  15.    }  
Run the Application and see the results.
 


Here, call MethodA, which will give the caller file path as the complete path of the source code file, name of the method in which it is being called, i.e. Main and the line number in the source code file, where MethodA is being called (which is 16 in our case). 
 
Hence, it becomes very helpful to use these parameters, when we need to perform the exception or normal logging in the Application. Hope, you enjoyed reading it. Happy coding. 


Similar Articles