Skip to content
This repository has been archived by the owner on May 1, 2024. It is now read-only.

Commit

Permalink
Add overload for Set<T>() with custom IEqualityComparer (#113)
Browse files Browse the repository at this point in the history
  • Loading branch information
SSchulze1989 authored Jun 11, 2022
1 parent cd143b5 commit 7115907
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
10 changes: 8 additions & 2 deletions src/MvvmBlazor.Core/ViewModel/ViewModelBase.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace MvvmBlazor.ViewModel;
namespace MvvmBlazor.ViewModel;

public abstract class ViewModelBase : INotifyPropertyChanged
{
Expand All @@ -10,7 +10,13 @@ public abstract class ViewModelBase : INotifyPropertyChanged

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

protected bool Set<T>(ref T field, T value, IEqualityComparer<T> equalityComparer, [CallerMemberName] string? propertyName = null)
{
ArgumentNullException.ThrowIfNull(equalityComparer);
if (!equalityComparer.Equals(field, value))
{
field = value;
OnPropertyChanged(propertyName!);
Expand Down
39 changes: 38 additions & 1 deletion src/MvvmBlazor.Tests/ViewModel/ViewModelBaseTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace MvvmBlazor.Tests.ViewModel;
namespace MvvmBlazor.Tests.ViewModel;

public class ViewModelBaseTests
{
Expand Down Expand Up @@ -76,11 +76,48 @@ void TestField<T>(ref T field, T value)
TestField(ref double1, 2.3);
}

[Fact]
public void Set_returns_False_with_custom_equality_comparer()
{
var mockEq= new StrictMock<IEqualityComparer<int>>();
mockEq.Setup(x => x.Equals(It.IsAny<int>(), It.IsAny<int>()))
.Returns(true)
.Verifiable();

var vm = new TestViewModel();
var int1 = 1;
var res = vm.SetProperty(ref int1, 2, mockEq.Object, "Foo");

res.ShouldBe(false);
mockEq.Verify();
}

[Fact]
public void Set_returns_true_with_custom_equality_comparer()
{
var mockEq= new StrictMock<IEqualityComparer<int>>();
mockEq.Setup(x => x.Equals(It.IsAny<int>(), It.IsAny<int>()))
.Returns(false)
.Verifiable();

var vm = new TestViewModel();
var int1 = 1;
var res = vm.SetProperty(ref int1, 1, mockEq.Object, "Foo");

res.ShouldBe(true);
mockEq.Verify();
}

private class TestViewModel : ViewModelBase
{
public bool SetProperty<T>(ref T field, T value, string? propertyName = null)
{
return Set(ref field, value, propertyName);
}

public bool SetProperty<T>(ref T field, T value, IEqualityComparer<T> equalityComparer, string? propertyName = null)
{
return Set(ref field, value, equalityComparer, propertyName);
}
}
}

0 comments on commit 7115907

Please sign in to comment.