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.
- class Program
- {
- static void Main(string[] args)
- {
- MethodA();
- Console.ReadKey();
- }
-
- private static void MethodA([CallerMemberName] string memberName = null, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = 0)
- {
- Console.WriteLine("Member is:" + memberName);
- Console.WriteLine("Path is:" + filePath);
- Console.WriteLine("Linenumber is:" + lineNumber);
- }
- }
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.