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

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

Full course on design patterns

Convert your MIDI keyboard/pad into a resharper code navigator!
Starting a new chapter at Lijnco
Starting a new chapter at Lijnco

A little more than 2 years ago, I started working at vitas. During my time at vitas, I got the chance to work at 3 different companies and in the meantime get 5 certificates. The last company (Lijnco) now offered me a permanent position! I’m really exited and enjoy working for Lijnco. The thing that appeals to me the most is the diversity in the projects: every project is different and every project is a new oppertunity to do it a little better and a little more efficient. Besides that, the more projects we do, the bigger the chance that we can reuse code. That highly increases efficiency.