Showing posts with label CallerMemberName. Show all posts
Showing posts with label CallerMemberName. Show all posts

Sunday, February 14, 2016

CallerMemberName vs. nameof() in INotifyPropertyChanged

Last month, we took a look at some of the framework and language changes that make it easier to implement INotifyPropertyChanged in our classes. Two of those changed included the "CallerMemberName" attribute and the "nameof()" expression.

Antoine left a great question since the functionality of "CallerMemberName" and "nameof()" seem so similar:
I don't see the point of using nameof() instead of the CallerMemberName though, is it about performance?
Let's take a closer look, first to see if there are any performance differences, and then see an example of why I prefer to use "nameof()": calculated properties.

Review: Using a String Parameter Directly
Let's look at why we want to use either "CallerMemberName" or "nameof()". For this, we'll do a quick review of how we implemented INotifyPropertyChanged before we had these.


This is a typical implementation of INotifyPropertyChanged (although you'll probably notice that we're using the null-conditional operator that we learned about before).

We could then call "RaisePropertyChanged" in our property setter by passing in the name of the property as a string:


This works, but wherever we have quoted strings, we have good places for things to break. For example, if we type the name of the property incorrectly, it will not work. If we change the name of our property, it's likely that our refactoring tool will not change the string, and it will not work.

So we'd like an option where we don't have to use a quoted string for the property name.

Review: Using "CallerMemberName" Attribute
One option is to use the "CallerMemberName" attribute (which was added to the framework in .NET 4.5), we put the attribute into our implementation of INotifyPropertyChanged:


Because the "CallerMemberName" attribute is placed before the first parameter of our "RaisePropertyChanged" method, the name of the calling item will be substituted here. So that means our property setter can look like this:


Notice that we do not pass a parameter to "RaisePropertyChanged". But because we have the attribute on the parameter, the string "FirstName" (the name of our property) is passed in automatically.

This fixes our initial problem because we no longer have a quoted string to worry about.

For more information on the "CallerMemberName" attribute, see "Using the CallerMemberName Attribute for Better XAML Data Binding".

Review: Using the "nameof()" Expression
A new option that we got with C# 6 (and the Visual Studio 2015 compiler) is the "nameof()" expression. To use this, we don't need to do anything special with our implementation of "INotifyPropertyChanged":


Notice that this implementation is exactly the same as our first example where we use the string parameter directly.

But instead of using a string parameter, we use the "nameof()" expression in the property setter:


When we use "nameof(FirstName)" in our code, it will pass the string "FirstName" as a parameter to "RaisePropertyChanged", so we get the correct value. And this has the added benefit of not being a quoted string.

This means that if we type "FirstName" incorrectly, we will get a compiler error. In addition, if we rename the property, our refactoring tools will automatically update the "nameof()" expression as well.

So why do I prefer "nameof()" to "CallerMemberName"?

Are There Performance Differences?
The first thing to do is look at performance. It turns out that all three of these implementations generate the same compiled code.

To take a look at the sample code, go to the "property-change-tracker" project on GitHub: jeremybytes/property-change-tracker. Inside of the "TestHelpers.Tests" project, there are classes that have all three implementations:


FakeClassStandardProperties
The "FakeClassStandardProperties" uses the quoted string parameters. If we look at the IL (intermediate language) that the compiler generates for the "FirstName" property, we see this code:


(Just a snippet). Notice the string "FirstName". This quoted string is used as the parameter for the next line, which is a call to "RaisePropertyChanged".

That's not much of a surprise, but let's look at the other classes.

FakeClassCallerMemberName
The "FakeClassCallerMemberName" uses the "CallerMemberName" attribute like we saw above. Let's look at the IL that is generated by the compiler:


This also has the quoted string "FirstName" which then gets used as a parameter for "RaisePropertyChanged". The compiler generates the same code as if we pass in the string directly.

So this means that there is no performance difference (at least at runtime), when we use the "CallerMemberName" attribute in this sceneario.

FakeClassNameOf
The "FakeClassNameOf" uses the "nameof()" expression like we saw above. Here's the IL that's generated:


Again we see the "FirstName" quoted string in our IL.

So this means that there is no performance difference if we use the "nameof()" expression in this scenario.

With no performance differences, why do I prefer "nameof()" over "CallerMemberName"? Let's take a look at another scenario: calculated properties.

Consistency and Calculated Properties
I've written a lot of user-facing applications. And quite often, these applications would have calculated properties -- properties that were based on 1 or more other properties. Here's an example:


If we have an order form that has both "Quantity" and "Price" properties, then we may also want a "TotalPrice" property that is calculated from these values.

In this case, if the "Quantity" is updated, then I want the "TotalPrice" property to be recalculated. In our data binding world, this means that we also need to call "RaisePropertyChanged" for our "TotalPrice" property.

Using the CallerMemberName Attribute
If we use the "CallerMemberName" attribute in this scenario, then our "Quantity" property may look like this:


The first "RaisePropertyChanged" (without a parameter), will get "Quantity" passed in. But for the second call to "RaisePropertyChanged", we need to explicitly pass a parameter so that we can also raise the PropertyChanged event for "TotalPrice".

Now, we know that using a hard-coded string here is not a good idea. That's the whole reason we want to use one of these other features. So, it makes more sense to update the code like this:


So the first call to "RaisePropertyChanged" (without the parameters) still raises the PropertyChanged event for "Quantity", but then the second call will raise it for "TotalPrice". And again, we get the benefits of not using a hard-coded string here.

Consistency with the nameof() Expression
And this is where I want to take things one step further. If I only have *one* call to "RaisePropertyChanged", then I don't have to do much thinking -- of course, this will reference the current property.

But when I have *two* calls to "RaisePropertyChanged", and one of them doesn't have any parameters, I need to start thinking a little more. Instead of this, I'd rather just use the "nameof()" expression for both calls.


This gives my brain something that is really easy to process. Without having to think about details, I know that this raises the PropertyChanged event for both "Quantity" and "TotalPrice".

Wrap Up
The "CallerMemberName" attribute and the "nameof()" expression both give us the same key benefits: (1) they eliminate the quoted string in our properties, and (2) they don't affect runtime performance.

But once we start to look at other scenarios -- like having calculated properties -- we see that "nameof()" can give us consistency in our properties that makes them easier to read and understand. And when we're dealing with code, human readability is a key feature.

In the applications I've spent most of my career with, calculated properties are pretty common. Because of that, I prefer the "nameof()" expression. But if you have classes that have no calculated properties (which is common when using entity classes), you may get better readability by using the "CallerMemberName" attribute.

A big part of making these types of decisions is to understand our environment. This helps us make the right decision for our particular application.

Happy Coding!

Sunday, January 3, 2016

The Evolution of INotifyPropertyChanged

When we implement the INotifyPropertyChanged interface, it's pretty common for us to copy code from a previous implementation or use a shared base class. What we don't normally do is review the code that we've been reusing.

But there are some features in .NET 4.5 and 4.6 that we can use to improve our implementation. Let's take a look at those to see how we can reduce our code without reducing functionality or safety.

Update: As Andrew points out in the comments; this article previously used the incorrect terminology for the null-conditional operator "?.". This has been corrected.

A Bit of Background
I really love data binding in XAML; it's extremely flexible and powerful. But in order for data binding to work appropriately, we need to implement the INotifyPropertyChanged interface in our data classes.

Original Implementation
The INotifyPropertyChanged interface only has a single member: the PropertyChanged event. To make it easier to raise this event, it's pretty common to create a helper method. Common names for this are "OnPropertyChanged" or "RaisePropertyChanged" (I prefer "RaisePropertyChanged").

So here's an implementation that I use to use:

Original Implementation (could be better)

This shows our helper method (RaisePropertyChanged) that takes the property name as a string. This is used to create the event args and then invoke the event.

This notifies the UI that anything bound to this property needs to be updated. If the event is called with a "null" parameter, then it is the same as notifying that all the properties have been updated.

To raise the event, we call "RaisePropertyChanged" in the setter for our properties:

Original Property Implementation (pre .NET 4.5)

If the value of the property has changed, then we set the property and then raise the event using a string value for the parameter.

Safer Implementation
This code worked, but it can be improved. First, let's look at it from a thread-safety perspective. It's possible that the PropertyChanged event could be updated in between the null check and the code to invoke the event.

To make things safer, we should use an intermediate variable:

Safer Implementation (pre .NET 4.5)

By using the "handler" variable, we create a copy the PropertyChanged event. Since this is a local variable, we know that it will not be updated in between the null check and the invocation of the event.

This gives us a thread-safe implementation of our "RaisePropertyChanged" method. (Again, thanks to Brian Lagunas for pointing this out to me.)

Improvements with .NET 4.5
The previous code works, and it will continue to work, but it does have some shortcomings. First is the use of the string parameter.

Original Property Implementation (pre .NET 4.5)

Hard-coded strings are rarely a good idea. If we happen to type the string incorrectly, then the data binding will not work as expected. This is especially frustrating to debug because there are no runtime errors; the UI elements are simply not updated like we want them to be.

In addition, if we change the name of our property, we need to make sure to update the string as well. Refactoring tools have gotten better; many of them have the option to update strings and comments when we rename a property. But it's possible to miss updating the string parameter.

Using the CallerMemberName Attribute
In .NET 4.5, we got a new attribute that can help us with our string problem: CallerMemberName. You can get a full description of how it works here: Using the CallerMemberName Attribute for Better XAML Data Binding.

The short version is that we can add the attribute to our INotifyPropertyChanged implementation:

Implementation with CallerMemberName Attribute (.NET 4.5)

Notice the attribute before the parameter. This value will automatically be populated with the name of the object calling this method.

Note: This is the non-thread-safe version of the code (it's taken from the example code in the article mentioned above). We should add the intermediate variable to make things safer.

With this new attribute in place, we can now update our properties as follows:

Property Implementation with CallerMemberName (.NET 4.5)

Notice that when we call "RaisePropertyChanged", we no longer pass in a parameter. Instead, we rely on the fact that "ProgressPercentage" (the name of our property) will automatically be passed because of the "CallerMemberName" attribute.

This gives us the advantage of no longer having a hard-coded string in our code. So we don't have to worry about typos or missed updates if we rename things.

Improvements with Visual Studio 2015
The previous code works (and will continue to work), but there are a couple of new features that came in with C# 6 that we can use. Since this is language/compiler related, we can use these with earlier version of .NET as long as we use the Visual Studio 2015 compiler to build the code.

"nameof" Expression
The "nameof" expression can get us the string name of a variable, type, or member. This is new in C# 6. Check out MSDN for more information: nameof (C# and Visual Basic Reference).

This lets us create our properties like this:

Property Implementation with "nameof" Expression (.NET 4.6)

Instead of passing a hard-coded string to "RaisePropertyChanged", we use "nameof" to generate the string for us. The end result is the same: we will pass the string "ProgressPercentage" to our method. The difference is that we will get a compile-time warning if we typo "ProgressPercentage" since this references the property.

In addition, if we use a refactoring tool to rename our property, the reference in "nameof" will get updated as well.

Using "nameof" will work with or without the "CallerMemberName" attribute.

Null-Conditional Operator
Another feature of C# 6 that we can use is the null-conditional operator (also called the "Elvis operator"). This takes of the form of "?.", and it combines a method or property reference with a null check.

Let's look at our INotifyPropertyChanged implementation to see how this operator works:

Original Implementation (could be better)

Compared to:

Implementation with "?." (.NET 4.6)
If the "PropertyChanged" event is null (meaning there are no event handlers hooked up to it), then everything after the "?." is ignored.

If "PropertyChanged" is not null, then the "Invoke" method is called. Note: calling "Invoke" explicitly is the equivalent of calling "PropertyChanged" with the parameters in the prior example.

The best thing about the null-conditional operator is that it is thread safe. This means that we no longer need the intermediate variable that we use earlier. So we end up with a very compact method that is thread safe.

Combining Features
We can also combine the "CallerMemberName" attribute with the null-conditional operator. Whether we do this depends on how we want to do our property code: either using no parameter or the "nameof" expression.

Reviewing Implementations
It's really easy for us to keep using the code that we're comfortable with. The "INotifyPropertyChanged" interface is especially prone to this. It is treated like boiler-plate code that has a consistent implementation. Because of this, we don't often review the code (as long as is continues to work).

I've described a very simple implementation here. Often people will use a base class or more involved implementation to make it easier to create properties. You can check out Dan Rigby's series of articles for some options on that.

From time to time, we should take a look at our boiler-plate implementations to see if they can be improved. In the case of "INotifyPropertyChanged", the "nameof" expression makes our code less brittle and easier to maintain. In addition, we can use the null-conditional operator to improve readability while still maintaining thread safety.

We'd never know about this without taking time for review.

Happy Coding!

Monday, October 6, 2014

Using the CallerMemberName Attribute for Better XAML Data Binding

I really like XAML (in case you haven't figured it out yet). The data binding mechanism is pretty awesome -- you can data bind to properties of other controls, data bind to properties of data objects in code, and even data bind to incompatible datatypes using a value converter. I often show this last feature by data binding a background color to a DateTime property -- this let's me have different colored backgrounds for records based on a decade.

But it's not magic. In order to for the data binding to work well with our C# objects, we need to implement the INotifyPropertyChanged interface. It's not a show-stopper, but it is a bit of a hassle. It turns out that we can use the CallerMemberName attribute (which we got in .NET 4.5) to make things a bit better.

Let's look at an example.

Standard INotifyPropertyChanged Implementation
For our example, we'll use a prior example that uses the BackgroundWorkerComponent with the MVVM design pattern. You can get the code sample here: CallerMemberName Attribute Sample.

This is a WPF application where the UI elements are data bound to properties in a view model. Here's what the application looks like when it's running:


The part that we'll be looking at is the progress bar that's right in the middle. The value of the progress bar is data bound to a property called "ProgressPercentage". But in order for the UI to get notified when we change the value in the code, we need to raise a property changed event. This is normally done by implementing the INotifyPropertyChanged interface on the view model.

Here's a typical implementation of INotifyPropertyChanged (this is in the "MainViewModel.cs" file):


Notice that we have a "PropertyChanged" event. This is an event that is specified by the interface. And generally, we also include a method that makes it really easy to raise this event. In this example, this is the "RaisePropertyChanged" method.

And we call this method in the setter of our properties. Here's the "ProgressPercentage" property:


So, if we follow the logic, when we set our property, it calls the "RaisePropertyChanged" method and passes in the name of the property as a string.

Then the "RaisePropertyChanged" method uses that parameter to pass the name of the property in the event args, and it raises the "PropertyChanged" event.

This alerts the UI that the "ProgressPercentage" property has been modified and that any UI elements that are data bound to this property should be updated.

Default Parameter
There's one other thing to notice about our "RaisePropertyChanged" method: it has a default value for the parameter:


This means that if do not pass in any value, the "propertyName" parameter will be null. If we pass "null" on to the PropertyChanged event, then it alerts to UI to update *all* data bound elements.

This is a great way to refresh an entire screen. But it is also very inefficient. If we send update alerts for values that haven't changed, then we're just wasting computation cycles. So we generally want to target our updates as much as possible.

The Problem of String Parameters
There is a bit of a problem with having a string parameter in this case. What happens if we type the name of the property wrong when we call "RaisePropertyChanged"? Nothing happens. Our UI doesn't update as we expect. And we don't get any compile-time checking on this because it's just a string.

We need to think about refactoring as well. What happens if we rename the property? Refactoring tools are good about renaming any references to the property we renamed, but they aren't always good about updating strings that might match the value. (And when the refactoring tools do offer this option, they don't often have it selected by default.)

It's easy enough to create a helper method that allows us to pass in something other than a string. The Prism framework includes an implementation that let's you pass in a lambda expression. This has the advantage of being compiled (so no worries about typos), and it also will get updated automatically by refactoring tools if we rename it.

So that introduces us to the situation. What can we do to improve it?

Using the CallerMemberName Attribute
In .NET 4.5, we got a new attribute: "CallerMemberName". When we use this attribute with a parameter, it will automatically fill in the name of whoever made the method call. The best way to understand this is to add it to our example.

In order to use this attribute, we first need to add a using statement to System.Runtime.CompilerServices:

Here's our updated "RaisePropertyChanged" method:


The only difference is that we added "[CallerMemberName]" before our parameter. Now, if we do not include an explicit parameter, the name of the caller will be used as the default value.

Let's update our "ProgressPercentage" property to remove the string parameter:


Now we no longer have to worry about the "ProgressPercentage" string in our code. If we run our application, we will see that it behaves exactly the same way that it did before.

And to show that we are getting the value that we want, we can set a breakpoint an look at the value that is coming in to the "RaisePropertyChanged" method:


This shows that even though we don't have any parameter in our source code, a value still gets inserted for us.

Updating All Properties
As mentioned above, we can pass in a "null" to notify the UI that all of the properties have been updated. But we can't just rely on the default parameter value anymore. If we leave out the parameter, it will default to the CallerMemberName.

But we can still explicitly pass in a null:


This gives us the results we expect:


So we can still update all of the properties if we need to.

Are There Performance Concerns?
When looking at this code, it looks like it's using reflection in order to figure out the value for the parameter. Reflection is slooooow, so this should be a concern. But we don't need to be concerned about this. One hint is that the namespace is "System.Runtime.CompilerServices".

The magic of "CallerMemberName" happens at compile-time. So, the resulting code is no different than if we had included the string explicitly in our code.

Don't believe me? Let's look at the IL that is generated:


This shows that the "RaisePropertyChanged" method is still being called with a static string parameter ("ProgressPercentage"). This means that our compiled code is just as efficient as if we had included the string in our source code.

One Requirement
There is one requirement when we use the "CallerMemberName" attribute with a method parameter: the parameter must have a default value. In our case, we have a default of "null" specified, but the default can be any valid value. The reason for this requirement is that the compiler sticks in the parameter value from the attribute in a similar way to how default parameter values are handled. So this will only work if there is a default for the parameter.

Wrap Up
We can use the "CallerMemberName" attribute to make our implementation of INotifyPropertyChanged much better. Instead of passing in hard-coded strings, we let the compiler fill in the value for us.

This eliminates the problem of having typos in the parameter or having incorrect values after renaming a property. This is especially frustrating with XAML data binding because we would not get any errors telling us what is wrong -- the binding simply would not work the way that we expect it to.

I like to eliminate these types of problems wherever possible. It turns out that the "CallerMemberName" attribute can help us with this.

Happy Coding!