-4

Given this code:

    public ICommand CopyCmd { get; set; }

    string _fullName;

    public string FullName
    {
        get => _fullName;
        set => SetProperty(ref _fullName, value);
    }

Why is it that the command can be handled with a { get; set; } but the name required my developer to add a backing field.

Alan2
  • 23,493
  • 79
  • 256
  • 450

2 Answers2

2

Because of SetProperty method. It looks like kind of implementation of INotifyPropertyChanged pattern. So, your view need to know when FullName value is changed.

Backs
  • 24,430
  • 5
  • 58
  • 85
2

The CopyCmd property in the question is an auto-implemented property. It is equivalent to this code:

private ICommand _CopyCmd;
public ICommand CopyCmd {
   get { return CopyCmd;}
   set { _CopyCmd = value;  }
}

In fact, the only difference between the above and what the compiler really does is the actual produced IL uses a different name than _CopyCmd which is not legal for C#, such that you can't accidently create a name in your own code which will conflict with the backing field.

The FullName property, though, does more work in the set block. You can do anything in a set block, but as soon you do more than assign the value to a backing field you can't use an auto-implemented property anymore.

In this case, the code also calls the SetProperty() method, which matches a convention typically associated with INotifyPropertyChanged. This makes it easy to have an event you can subscribe to which is raised any time this property changes.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794