Skip to content

Commit

Permalink
Add new constructor to AvaloniaDictionary and include unit tests #17311
Browse files Browse the repository at this point in the history
… (#17312)

* Give AvaloniaDictionary new .ctor and add Tests for it
#17311

* AvaloniaDictionary accept IDictionary as init collection

---------

Co-authored-by: Julien Lebosquain <[email protected]>
  • Loading branch information
IoannTerrible and MrJul authored Jan 23, 2025
1 parent fce5682 commit 58dacb0
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
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)
{
_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"]);
}



}
}

0 comments on commit 58dacb0

Please sign in to comment.