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

Add new constructor to AvaloniaDictionary and include unit tests #17311 #17312

Merged
merged 3 commits into from
Jan 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/Avalonia.Base/Collections/AvaloniaDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,21 @@ public AvaloniaDictionary(int capacity)
_inner = new Dictionary<TKey, TValue>(capacity);
}

/// <summary>
/// Initializes a new instance of the <see cref="AvaloniaDictionary{TKey, TValue}"/> class using an IDictionary.
/// </summary>
public AvaloniaDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey>? comparer = null)
{
if (dictionary != null)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: you can remove this check and the throw below. Let the Dictionary's constructor throw on its own, as its documented to do so. There's no real point in checking the same thing several times.

{
_inner = new Dictionary<TKey, TValue>(dictionary, comparer ?? EqualityComparer<TKey>.Default);
}
else
{
throw new ArgumentNullException(nameof(dictionary));
}
}

/// <summary>
/// Occurs when the collection changes.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System;
using System.Collections.Generic;
using System.Collections.Specialized;

using Avalonia.Collections;
using Avalonia.Data.Core;

using Xunit;

namespace Avalonia.Base.UnitTests.Collections
Expand Down Expand Up @@ -156,5 +158,34 @@ public void Clearing_Collection_Should_Raise_PropertyChanged()

Assert.Equal(new[] { "Count", CommonPropertyNames.IndexerName }, tracker.Names);
}

[Fact]
public void Constructor_Should_Throw_ArgumentNullException_When_Collection_Is_Null()
{
Assert.Throws<ArgumentNullException>(() =>
{
var target = new AvaloniaDictionary<string, string>(null, null);
});
}


[Fact]
public void Constructor_Should_Initialize_With_Provided_Collection()
{
var initialCollection = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" }
};

var target = new AvaloniaDictionary<string, string>(initialCollection, null);

Assert.Equal(2, target.Count);
Assert.Equal("value1", target["key1"]);
Assert.Equal("value2", target["key2"]);
}



}
}
Loading