C# MVVM – Are Getters in XAML View-Models Bad?

cmvvmxaml

I've recently had an argument with a colleague about using getters (without setters) in a view-model classes used by XAML.

Example:

public string FullName
{
   get
   {
      return $"{FirstName} {LastName}";
   }
}
//call OnPropertyChanged("FullName") when setting FirstName or LastName

His argument was that you should only ever create get/set pairs which use a private field (with the setter raising the PropertyChanged event if the value has indeed been changed).

Example:

private string _fullName;
public string FullName
{
   get
   {
      return _fullName;
   }
   set
   {
      if (value != _fullName)
      {
         _fullName = value;
         OnPropertyChanged("FullName");
      }
   }
}
//Set FullName when setting FirstName or LastName

I, on the other hand, think it's fine to use getters (which calculate the output on the fly), provided they aren't updated all the time via too many PropertyChanged calls.

I don't think my colleagues approach is bad – I just think it's way more busy work which might simply be not needed. However he was sure my approach is bad and should be avoided at all cost.

As a counter example I pointed out that the MVVM base class from DevExpress has RaisePropertyChanged and RaisePropertiesChanged (for refreshing multiple properties) methods ready for use – both of which wouldn't be needed if all the properties were get/set pairs (the DevExpress base class also exposes a SetProperty method for use in setters, which also includes a PropertyChanged call). His argument was that "well, people are stubborn, keep doing it wrong, so DevExpress simply added those methods to make sure people are happy" which I found… odd, to say the least.

So what's the take here? Is it bad design to use getters in view-models designed to be used by XAML?

EDIT:
I forgot to mention… my colleague also made the claim that using get/set pairs will always be faster. That does seem to be true as far as updating the UI is concerned, but he also used this as an argument that getters shouldn't ever be used. The whole argument started when I had a bit of performance issues when populating a data grid with more (i.e. 12k) rows where my VM used quite a few getters…

Best Answer

Your coworker is incorrect.

When working with UI logic in MVVM, it's common to have properties for binding that are derived from other data.

In these cases, you don't want to create another private member - that just adds a point of failure with no benefit.

Side note:

If you're using C# 6 then instead of hardcoded strings you can do

OnPropertyChanged(nameof(FullName));

This way, you'll get a compiler error if you change the name of the FullName property but forget to update corresponding calls to OnPropertyChanged.