Skip to content

Commit 2b2955e

Browse files
authored
Fixed bug in ReadOnlyDictionary's IDictionary.this[object] implementation. This method didn't adhere to IDictionary's contract to return null on a missing key. (#36926)
1 parent 79d2f47 commit 2b2955e

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,14 @@ void IDictionary.Remove(object key)
161161
return null;
162162
}
163163

164-
return this[(TKey)key];
164+
if (m_dictionary.TryGetValue((TKey)key, out TValue value))
165+
{
166+
return value;
167+
}
168+
else
169+
{
170+
return null;
171+
}
165172
}
166173
set => throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
167174
}

src/libraries/System.ObjectModel/tests/ReadOnlyDictionary/ReadOnlyDictionaryTests.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,20 @@ public static void GetValuesTests()
142142
helper.Values_get_Tests();
143143
}
144144

145+
/// <summary>
146+
/// Tests that the explicit IDictionary.Item[] implementation returns null on a non-existing key.
147+
/// </summary>
148+
[Fact]
149+
public static void IDictionaryItemTests()
150+
{
151+
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
152+
new KeyValuePair<int, string>(1, "one")
153+
};
154+
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
155+
IDictionary dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
156+
Assert.Null(dictionary[2]);
157+
}
158+
145159
/// <summary>
146160
/// Tests that items can be retrieved by key from the Dictionary.
147161
/// </summary>

0 commit comments

Comments
 (0)