Getting Caller Information using Caller Info attributes is initially introduced with .NET Framework 4.5. It can be real handy if you want to write a module for tracing, debugging etc.
Following are the Caller Info Attributes which are defined in System.Runtime.CompilerServices namespace.
- CallerMemberNameAttribute
- Method or property name of the caller.
- CallerFilePathAttribute
- Full path of the source file that contains the caller. This is the file path at compile time.
- CallerLineNumberAttribute
- Line number in the source file at which the method is called.
Let’s see a very simple example.
using System;
using System.Runtime.CompilerServices;
namespace CallerInfoDemo
{
class Program
{
static void Main(string[] args)
{
TraceMessage("Caller Info Attributes...");
}
static void TraceMessage(string message = "",
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Console.WriteLine("Message: " + message);
Console.WriteLine("Member name: " + memberName);
Console.WriteLine("Source file path: " + sourceFilePath);
Console.WriteLine("Source line number: " + sourceLineNumber);
}
}}
Please note the optional parameters which are marked with Caller Info Attributes in the TraceMessage method.
This will print the following output.
Output |
Please check the following post to get to know about a scenario where Caller Information can be used very effectively.
INotifyPropertyChanged Without Hardcoding the Property NameDownload the sample from my SkyDrive.
Happy Coding.
Regards,
Jaliya
No comments:
Post a Comment