Skip to content

Instantly share code, notes, and snippets.

@jnm2
Last active July 1, 2024 01:36
Show Gist options
  • Save jnm2/df690bc7278371d735c546c57e787b6e to your computer and use it in GitHub Desktop.
Save jnm2/df690bc7278371d735c546c57e787b6e to your computer and use it in GitHub Desktop.

Field use cases

Initial community discussion thread: dotnet/csharplang#140

First-access ("lazy") initialization

public List<int> Prop => field ??= new();
public Foo Prop => LazyInitializer.EnsureInitialized(ref field, CalculateFoo);

Default if not set

public string Prop { get => field ?? parent.Prop; set; }

Default if reset to default

public string Prop
{
    get => field ?? parent.Prop;
    set => field = value == parent.Prop ? null : value;
}

Clean

public string Prop { get; set => field = value.Trim(); }

Validate

public int Prop
{
    get;
    set => field = value < 1 ? throw new ArgumentOutOfRangeException(...) : value;
}

Do things before or after setting

public INotifyCollectionChanged? Collection
{
    get;
    set
    {
        field?.CollectionChanged -= OnCollectionChanged;
        field = value;
        field?.CollectionChanged += OnCollectionChanged;
    }
}

Ignore redundant sets

public int Prop
{
    get;
    set
    {
        if (field == value) return;
        field = value;
        CalculateTotals();
    }
}

INotifyPropertyChanged (INPC)

This is one of the most vociferously popular use cases, for those using INPC today.

class C : ViewModel
{
    public string Prop { get; set => Set(ref field, value); }
}

// Common genre of helper method:
abstract class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    protected bool Set<T>(
        [NotNullIfNotNull(nameof(value))] ref T field,
        T value,
        [CallerMemberName] string? propertyName = null);
}

Default struct values

Console.WriteLine(default(S).DefaultsToTrue); // True

struct S
{
    public bool DefaultsToTrue { get => !field; set => field = !value; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment