WPF notify helper – C# 5.0

So after looking at the documentation on what’s new in C# 5.0, I read about the feature that you can get a function’s caller information that looks like the following.

public void DoProcessing()
{
    TraceMessage("Something happened.");
}
 
public void TraceMessage(string message,
        [CallerMemberName] string memberName = "",
        [CallerFilePath] string sourceFilePath = "",
        [CallerLineNumber] int sourceLineNumber = 0)
{
    Trace.WriteLine("message: " + message);
    Trace.WriteLine("member name: " + memberName);
    Trace.WriteLine("source file path: " + sourceFilePath);
    Trace.WriteLine("source line number: " + sourceLineNumber);
}

This snippet is stolen straight from msdn.
http://msdn.microsoft.com/en-us/library/hh534540(v=vs.110).aspx

I also saw another example of where this would be used for WPF classes that implement INotifyPropertyChanged. The example looked liked the following

protected void RaisePropertyChanged([CallerMemberName] string memberName = "")
{
    RaisePropertyChanged(memberName);
}

This actually reminded me of what I did in some of my WCF services to get the calling method name displayed when invoked, so that I could print out who called it(using WindowsIdentity) and what method they called. However, I accomplished it using the StackTrace class and StackFrame. So I quickly came with a way to get similar functionality until 5.0 is ready for my eager hands.

The result looks like the following

protected void RaisePropertyChanged()
{
    var frame = new StackTrace().GetFrame(1);
    string name = frame.GetMethod().Name.Substring(4);
    RaisePropertyChanged(name);
}

So when you create your Bindable properties you could simplify code that would look like

public const straing ProgressValuePropertyName = "ProgressValue";
private double _progressValue;
public double ProgressValue
{
    get { return _progressValue; }
    set { _progressValue = value; RaisePropertyChanged(ProgressValuePropertyName); }
}

into

private double _progressValue;
public double ProgressValue
{
    get { return _progressValue; }
    set { _progressValue = value; RaisePropertyChanged(); }
}

So while this is a small step forward, it’s still nowhere nearly as clean as using PostSharp and AOP to look like

[RaisePropertyChanged]
public double ProgressValue { get; set; }

Thinking about my brain dump right now, I’m going to play with the Roslyn services to see if that is going to generally offer the same capabilities as PostSharp.

Leave a Reply