December 5, 2014

CallerMemberNameAttribute in .NET 4.5

Use of "CallerMemberNameAttribute" for an IPropertyNotifyChanged base class implementation
More declaration info can be found here

I found that this did not work in VS 2010 but did work in VS 2013 as it is compiler dependent. You need to install KB2468871 on top of .net 4 framework to be able to use. Alternatively, you can simply define the attribute yourself to get it to work.
namespace System.Runtime.CompilerServices
{
  /// 
  /// Allows you to obtain the method or property name of the caller.
  /// 
  [AttributeUsageAttribute(AttributeTargets.Parameter, Inherited = false)]
  public sealed class CallerMemberNameAttribute : Attribute { }
}
Here is an example of how to use it to make a simple logger (only 1 method shown):
class SimpleLogger 
{
...
 public void Error(
   [CallerMemberName] string memberName = "",
   [CallerFilePath] string sourceFilePath = "",
   [CallerLineNumber] int sourceLineNumber = 0,
   string message)
 {
    Debug.Write(" Method/Property=" + memberName);
    Debug.Write(" SourceFilePath=" + sourceFilePath);
    Debug.Write(" SourceLineNumber=" + sourceLineNumber);
    Debug.WriteLine(" - " + message);

 }
...
}
and invoking it:
SimpleLogger logger = new SimpleLogger();
...
catch(Exception ex)
{
  logger.Trace(" Exception caught " + ex.ToString()); // The attributed parameters are inserted by the compiler at compile time
}

No comments: