C# 5 Callerinfo Attribute

As application developer we log information related to execution (information or error) to log files. This information is helpful for tracing, debugging, and creating diagnostic tools. If the log message has file name, line number and function name it is easy to narrow down the issue file and function.

In C/C++ developer can use  __FILE__ , __LINE__ and __FUNCTION__ macros to print file name, function name and line information along with the log message.

Following code c++ code illustrate the usage

// logger function
void LogMessage(std::string caller ,std::string LogMessage)
{
	std::cout<<__FILE__<<":"<<__LINE__<<" - "<<caller<<" "<<LogMessage<<std::endl;
}
// main function
int main(int argc, char* argv[])
{
	LogMessage (__FUNCTION__,"Starting Application");
	return 0;
}

If you are .Net developer  prior to .Net 4.0  you would have used System.Diagnostics.StackFrameclass to get this information .

public class Program
{
	public static void LogMessage(String message)
	{
		// get access to caller stackframe
		StackFrame frame = new System.Diagnostics.StackTrace(true).GetFrame(1);
		String file = frame.GetFileName();
		int line = frame.GetFileLineNumber();
		String member = frame.GetMethod().Name;
		
		var s = String.Format("{0}:{1} - {2}: {3}", file, line, member, message);
		Console.WriteLine(s);
	}
	static void Main(string[] args)
	{
		LogMessage("Starting the application ...");
	}
}

In C# 5 and VB.Net 11 there is easier way of getting this information using CallerInfo attribute.By using Caller Info attributes, you can obtain information about the caller to a method.

You can obtain file path of the source code, the line number in the source code, and the member name of the caller.

Here is the sample which uses C#5 feature ( available in .Net 4.5 )

public class Program
{
	public static void LogMessage(    
	string message,
	[CallerFilePath] string file = "",
	[CallerLineNumber] int line = 0,
	[CallerMemberName] string member = "")
	{
		var s = string.Format("{0}:{1} - {2}: {3}", file, line, member, message);
		Console.WriteLine(s);
	}
	static void Main(string[] args)
	{
		LogMessage("Starting the application ...");
	}
}

More information about Callinfo attribute can be found here
1. MSDN