Introduction
Sometime back, I was browsing through new features of VS 2012, and found one of the useful features called "Caller Information".
By using this "Caller Information" feature of C# 5.0, we can get the information about the caller to a method like method name, if any error occurs its line number. You can also get file path of the source code, line number of the caller method/function. This information can be useful in logging application, tracing, etc.
Using the Code
To demonstrate the above functionality, I have created a sample logging web application, if any error occurred it will log that information into text file. By using caller information attribute, we can easily get method name, file path and line number where error has occurred.
Caller Information attributes are defined in the System.Runtime.CompilerServices
namespace.
using System.Runtime.CompilerServices;
The below method will add message log with caller information optional parameter:
public void AddLog(string message, [CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Message: " + message);
sb.AppendLine("Member/Function name: " + memberName);
sb.AppendLine("Source file path: " + sourceFilePath);
sb.AppendLine("Source line number: " + sourceLineNumber);
string FileName = @"D:\" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".log";
if (File.Exists(FileName))
{
File.Delete(FileName); }
using (StreamWriter sw = File.CreateText(FileName))
{
sw.Write(sb.ToString()); sw.Close();
}
}
Here we have used the below attributes:
[CallerFilePathAttribute]
- This will give us full path of the source file that contains the caller.
[CallerLineNumberAttribute]
- By using this, get the line number in the source file at which the method is called.
[CallerMemberNameAttribute]
- Get method or property name of the caller.
Interesting Points
- We need to specify Caller Information attributes as optional
- We have to specify an explicit default value for each optional parameter.
- This can be very much useful in:
- Using tracing/logging
- Implementing the
INotifyPropertyChanged
interface when binding data. This will notify clients that a property value has changed.
- If we use Caller information within:
- Method, property, or event - Get the name of the method/property/event
- Constructor -
string
".ctor
"
Static
constructor - string
".cctor
"
- Destructor -
string
"Finalize
"