C# 5 in 2012: Verifying UI notifications with CallerMemberName
See how Visual Studio 2012-era C# could supply caller names for binding notifications, then test renames, helper methods and unchanged values.
Archive retrospective · Topic year 2012
In this article
Why renames could leave a stale desktop interface
A bound desktop label should change when the model changes. If the model sends a misspelled or outdated property name, the saved value can be correct while the user reads the old value. A common cause is copying the property name into a string argument that survives a rename. In the Visual Studio 2012 era, C# 5 introduced caller information for eligible optional parameters. A direct call from a property can supply the property name to a shared notification method. That does not decide when the event belongs in the model, or create a binding that the interface never configured. The example makes the name and number of events observable in a console program before attaching a real control. It also stays within the language syntax available in the period.
The compiler supplies a literal at the call site
CallerMemberName can decorate an optional string parameter. When the argument is omitted, the compiler uses the caller's member name. It does not inspect the execution stack to recover a name at runtime. That difference is visible when a refactor moves the call into another helper. The compiler can supply that helper's name even though the screen expects the property name. Check where the optional parameter is actually filled. If an intermediate method is useful, let it accept the outer caller's value and pass it on explicitly. A caller can also deliberately pass a different value. The compiler's job is to supply a name when the argument is omitted. It cannot infer what change a notification is supposed to represent. A test that checks the received name catches a helper refactor without requiring a full interface run.
Two equal assignments should raise one event in this example
The model tracks the number of pallets at a dock. The program first attaches a listener. It then assigns three, followed by the same value again. The first assignment changes the field and produces an event. The repeated value produces no event. The listener observes Pallets and the new value three. Some applications may deliberately use a repeated reading as a refresh signal, so that policy belongs in an explicit contract. In this fixture the assignment happens before raising the event. A listener that reads the model immediately must see the updated value. Check the output count as well as the name. That catches both a mistyped property and a duplicate event. A subsequent screen test should confirm the control binds to this model and receives the change.
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
public sealed class DockStatus : INotifyPropertyChanged
{
private int pallets;
public event PropertyChangedEventHandler PropertyChanged;
public int Pallets
{
get { return pallets; }
set
{
if (pallets == value) return;
pallets = value;
Notify();
}
}
private void Notify([CallerMemberName] string property = null)
{
var listener = PropertyChanged;
if (listener != null)
listener(this, new PropertyChangedEventArgs(property));
}
}
public static class Demo
{
public static void Main()
{
var dock = new DockStatus();
dock.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine("{0}: {1}", e.PropertyName, dock.Pallets);
};
dock.Pallets = 3;
dock.Pallets = 3;
}
}
// Expected output: Pallets: 3
Test a rename and any derived display values
Rename Pallets and prove that the event carries the new property name. Then check that the binding path in the interface names the same property. Updating the caller argument does not update every binding string. A utilization value derived from the pallet count may require its own notification. Identify this dependency before the application ships. Write down which fields should be set before a listener sees either change. Refreshing every property after each assignment can create extra work, especially if one property owns a large list. A small assertion over the event names and order distinguishes a targeted update from a full view refresh. That test survives a rename and also tells a later maintainer why the derived value was included.
Source locations are diagnostic context
C# also has caller attributes for a source file and a line number. Those values describe a location at compile time. A full path can reveal the directory layout of the machine that built the program. Logging only a file name is different from omitting the full string from the compiled package. Decide whether the destination needs the source location at all. A stable event code is preferable when you want an identifier that survives routine line changes. Here the method requests only the member name. Do not use a reported caller name as authority for a security or business decision. Besides its diagnostic purpose, the argument can be supplied explicitly. Record whether traces can leave the organization and which build produced them. That keeps convenient diagnostics tied to a sensible boundary.
Preserve a small test with the language assumptions
The sample can be checked with a suitable period compiler or a modern compiler targeting the old language version. Record which environment was used. A syntax check in a later compiler does not demonstrate that every old operating system or binding dependency was reproduced. Exercise the model with no listener, one listener, equal writes and a changed write. Try a call moved into an intermediate method and compare it to the direct call. Then attach the actual bound screen if it is part of the release. This separates three things that can fail independently: the compiler's optional argument, the model's event semantics and the interface's binding path. That separation is the useful lesson a small C# 5 example can still teach.
Reader discussion
What is the most important unanswered question about this topic?
No comments yet. Be the first to contribute.
Write a comment