diff --git a/csharp/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs b/csharp/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs index 766b4cb5db..5a8977d611 100644 --- a/csharp/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs +++ b/csharp/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs @@ -888,5 +888,17 @@ namespace Google.Protobuf.Collections Assert.DoesNotThrow(() => list.Capacity = 0, "Can set Capacity to 0"); Assert.AreEqual(0, list.Capacity); } + + [Test] + public void Clear_CapacityUnaffected() + { + var list = new RepeatedField { 1 }; + Assert.AreEqual(1, list.Count); + Assert.AreEqual(8, list.Capacity); + + list.Clear(); + Assert.AreEqual(0, list.Count); + Assert.AreEqual(8, list.Capacity); + } } } diff --git a/csharp/src/Google.Protobuf/Collections/RepeatedField.cs b/csharp/src/Google.Protobuf/Collections/RepeatedField.cs index 832e166943..56117fd325 100644 --- a/csharp/src/Google.Protobuf/Collections/RepeatedField.cs +++ b/csharp/src/Google.Protobuf/Collections/RepeatedField.cs @@ -279,8 +279,9 @@ namespace Google.Protobuf.Collections } /// - /// Gets and sets the capacity of the RepeatedField's internal array. WHen set, the internal array is reallocated to the given capacity. - /// The new value is less than Count -or- when Count is less than 0. + /// Gets and sets the capacity of the RepeatedField's internal array. + /// When set, the internal array is reallocated to the given capacity. + /// The new value is less than . /// public int Capacity { @@ -338,7 +339,10 @@ namespace Google.Protobuf.Collections /// public void Clear() { - array = EmptyArray; + // Clear the content of the array (so that any objects it referred to can be garbage collected) + // but keep the capacity the same. This allows large repeated fields to be reused without + // array reallocation. + Array.Clear(array, 0, count); count = 0; }