From 5be01ee65b987ef17e6418fbff5f161ed0f5cc87 Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Mon, 10 Aug 2015 08:47:07 +0100 Subject: Implement ICollection.CopyTo (using Array) for MapField views. --- .../src/Google.Protobuf.Test/Collections/MapFieldTest.cs | 14 ++++++++++++++ csharp/src/Google.Protobuf/Collections/MapField.cs | 13 ++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs b/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs index 08f1a19c..29c4c2a9 100644 --- a/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs +++ b/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs @@ -523,6 +523,20 @@ namespace Google.Protobuf.Collections keys.CopyTo(array, 1); CollectionAssert.AreEqual(new[] { null, "foo", "x", null }, array); } + + // Just test keys - we know the implementation is the same for values + [Test] + public void NonGenericViewCopyTo() + { + IDictionary map = new MapField { { "foo", "bar" }, { "x", "y" } }; + ICollection keys = map.Keys; + // Note the use of the Array type here rather than string[] + Array array = new string[4]; + Assert.Throws(() => keys.CopyTo(array, 3)); + Assert.Throws(() => keys.CopyTo(array, -1)); + keys.CopyTo(array, 1); + CollectionAssert.AreEqual(new[] { null, "foo", "x", null }, array); + } [Test] public void KeysContains() diff --git a/csharp/src/Google.Protobuf/Collections/MapField.cs b/csharp/src/Google.Protobuf/Collections/MapField.cs index 6dcdc100..004ff54b 100644 --- a/csharp/src/Google.Protobuf/Collections/MapField.cs +++ b/csharp/src/Google.Protobuf/Collections/MapField.cs @@ -735,7 +735,18 @@ namespace Google.Protobuf.Collections public void CopyTo(Array array, int index) { - throw new NotImplementedException(); + if (index < 0) + { + throw new ArgumentOutOfRangeException("arrayIndex"); + } + if (index + Count >= array.Length) + { + throw new ArgumentException("Not enough space in the array", "array"); + } + foreach (var item in this) + { + array.SetValue(item, index++); + } } } } -- cgit v1.2.3