03 November 2013 CI Team

Debugging and Logging Code are usually full of function names and so on just so you are able to find the right place in the code at the end. Of course there are several other reasons to find out who was the last one to open the code. The interface INotifyPropertyChanged is such an example because you need the names of the properties. <p>It’s possible to solve this static – but usually the refactoring doesn’t work out. .NET 4.5 offers a nice solution for this problem. I’m sure most of you have already heard about it but I just found out recently.

Caller Information

.NET 4.5 offers the option to decode three attribute parameter. These parameter are filled with “invocation” information’s.

CallerMemberName: shows the name of the chosen method or the property
CallerFilePath: shows the complete file path
CallerLineNumber: The line number of the invoke code

The attributes are situated in the System.Runtime CompilerServices namespace.

Example

1: class Program 2: { 3: static void Main(string[] args) 4: { 5: Log("Hello World..."); 6: Console.ReadLine(); 7: } 8: 9: public static void Log(string text, [CallerMemberName] string callerMemberName = "", 10: [CallerFilePath] string callerPath = "", 11: [CallerLineNumber] int callerLineNumber = 0) 12: { 13: Console.WriteLine("Invoked with: " + text); 14: Console.WriteLine("Caller {0} from File {1} (Ln: {2})", callerMemberName, callerPath, callerLineNumber); 15: } 16: }

If you take a look on the code with ILSpy you are going to find the right information’s:

1: internal class Program 2: { 3: private static void Main(string[] args) 4: { 5: Program.Log("Hello World...", "Main", "c:\\Users\\Robert\\Documents\\Visual Studio 2013\\Projects\\CallerInformationDemo\\CallerInformationDemo\\Program.cs", 14); 6: Console.ReadLine(); 7: } 8: public static void Log(string text, [CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerPath = "", [CallerLineNumber] int callerLineNumber = 0) 9: { 10: Console.WriteLine("Invoked with: " + text); 11: Console.WriteLine("Caller {0} from File {1} (Ln: {2})", callerMemberName, callerPath, callerLineNumber); 12: } 13: }

INotifyPropertyChanged

Take a look at the implementation of the INotifyPropertyChanged example.

Additional information’s are available in this blogpost.

Demo-Code on GitHub

You can find the demo application on GitHub.