Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How should we generate TrySet #149

Open
JohanLarsson opened this issue Aug 23, 2019 · 2 comments
Open

How should we generate TrySet #149

JohanLarsson opened this issue Aug 23, 2019 · 2 comments

Comments

@JohanLarsson
Copy link
Collaborator

JohanLarsson commented Aug 23, 2019

  • Always set
  • Notify if different.
  • EqualityComparer or RuntimeHelpers?
  • Names? Method & parameters.

/cc @jnm2

@JohanLarsson
Copy link
Collaborator Author

JohanLarsson commented Aug 23, 2019

Maybe:

protected bool TrySet<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
    if (EqualityComparer<T>.Default.Equals(field, value))
    {
        field = value;
        return false;
    }

    field = value;
    this.OnPropertyChanged(propertyName);
    return true;
}

@jnm2
Copy link
Collaborator

jnm2 commented Aug 23, 2019

The two candidates I like best (right now):

// Downside: boxing

protected bool TrySet<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
    if (RuntimeHelpers.Equals(field, value)) return false;
    field = value;
    OnPropertyChanged(propertyName);
    return true;
}
// Downside: can fail to raise the event and return true for things that an observer could care
// about which are ignored by Equals.

protected bool TrySet<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
    var shouldNotify = !EqualityComparer<T>.Default.Equals(field, value);
    field = value;
    if (shouldNotify) OnPropertyChanged(propertyName);
    return shouldNotify;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants