Skip to content

Commit 74150b4

Browse files
committed
Make this[int] throw on dictionaries
1 parent 77b9e5b commit 74150b4

2 files changed

Lines changed: 6 additions & 14 deletions

File tree

ValveKeyValue/ValveKeyValue.Test/EdgeCaseTestCase.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -732,9 +732,8 @@ public void DictAndListCollectionsHaveConsistentBehavior()
732732
Assert.That(dict.Count, Is.EqualTo(2));
733733
Assert.That(list.Count, Is.EqualTo(2));
734734

735-
// Integer indexer
736-
Assert.That((int)dict[0], Is.EqualTo(1));
737-
Assert.That((int)dict[1], Is.EqualTo(2));
735+
// Integer indexer (list-backed only)
736+
Assert.That(() => dict[0], Throws.InstanceOf<NotSupportedException>());
738737
Assert.That((int)list[0], Is.EqualTo(1));
739738
Assert.That((int)list[1], Is.EqualTo(2));
740739
});

ValveKeyValue/ValveKeyValue/KVObject.cs

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ public KVObject this[string key]
197197
}
198198

199199
/// <summary>
200-
/// Gets a child by index (for arrays and collections by insertion order).
200+
/// Gets a child by index (for arrays and list-backed collections).
201201
/// </summary>
202202
public KVObject this[int index]
203203
{
@@ -208,12 +208,12 @@ public KVObject this[int index]
208208
return GetArrayList()[index];
209209
}
210210

211-
if (ValueType == KVValueType.Collection)
211+
if (_ref is List<KeyValuePair<string, KVObject>> list && ValueType == KVValueType.Collection)
212212
{
213-
return GetCollectionByIndex(index);
213+
return list[index].Value;
214214
}
215215

216-
throw new NotSupportedException($"Integer indexer on a {nameof(KVObject)} can only be used when the value is an array or collection.");
216+
throw new NotSupportedException($"Integer indexer on a {nameof(KVObject)} can only be used when the value is an array or list-backed collection.");
217217
}
218218
}
219219

@@ -582,13 +582,6 @@ private bool TryInsert(string key, KVObject value, InsertionBehavior behavior)
582582
_ => [],
583583
};
584584

585-
private KVObject GetCollectionByIndex(int index) => _ref switch
586-
{
587-
Dictionary<string, KVObject> dict => dict.Values.ElementAt(index),
588-
List<KeyValuePair<string, KVObject>> list => list[index].Value,
589-
_ => throw new InvalidOperationException("Not a collection."),
590-
};
591-
592585
private IEnumerable<KeyValuePair<string, KVObject>> EnumerateArray()
593586
{
594587
var list = GetArrayList();

0 commit comments

Comments
 (0)