Fody: less code - more functionlity

Published: Jul 23, 2019 by Jenno Vink

PropertyChanged.Fody

When using the MVVM pattern in C# I think it’s very useful to use PropertyChanged.Fody. It injects code at compile time and as a result, the code becomes cleaner and better readable.

Before code:

public class Person : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    
    public string GivenNames { get; set; }
    public string FamilyName { get; set; }
    public string FullName => $"{GivenNames} {FamilyName}";
}

What gets compiled:

public class Person : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    string givenNames;
    public string GivenNames
    {
        get => givenNames;
        set
        {
            if (value != givenNames)
            {
                givenNames = value;
                OnPropertyChanged(InternalEventArgsCache.GivenNames);
                OnPropertyChanged(InternalEventArgsCache.FullName);
            }
        }
    }
    string familyName;
    public string FamilyName
    {
        get => familyName;
        set 
        {
            if (value != familyName)
            {
                familyName = value;
                OnPropertyChanged(InternalEventArgsCache.FamilyName);
                OnPropertyChanged(InternalEventArgsCache.FullName);
            }
        }
    }
    public string FullName => $"{GivenNames} {FamilyName}";
    protected void OnPropertyChanged(PropertyChangedEventArgs eventArgs)
    {
        PropertyChanged?.Invoke(this, eventArgs);
    }
}
internal static class InternalEventArgsCache
{
    internal static PropertyChangedEventArgs FamilyName = new PropertyChangedEventArgs("FamilyName");
    internal static PropertyChangedEventArgs FullName = new PropertyChangedEventArgs("FullName");
    internal static PropertyChangedEventArgs GivenNames = new PropertyChangedEventArgs("GivenNames");
}

What a tremendous improvement!

fody mvvm

Latest Posts

Using Windows PowerToys
Using Windows PowerToys

Streamline your windows experience

A new life
A new life

Hip hip hooray! Welcome to our planet

Stepping up my dotnet game!
Stepping up my dotnet game!

Full course on design patterns