Sobes.tech
Junior — Middle

How can a property change notification mechanism be implemented in data models in .NET?

sobes.tech AI

Answer from AI

In .NET, the INotifyPropertyChanged interface is commonly used to implement property change notifications in data models. It defines the PropertyChanged event, which is raised when a property's value changes.

Example implementation:

using System.ComponentModel;

public class Person : INotifyPropertyChanged
{
    private string name;
    public string Name
    {
        get => name;
        set
        {
            if (name != value)
            {
                name = value;
                OnPropertyChanged(nameof(Name));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

When the Name property changes, the OnPropertyChanged method is called, notifying subscribers that the property has changed. This is often used in the MVVM pattern to update the UI when data changes.