Skip to content

Commit d368735

Browse files
CopilotBillWagner
andauthored
Fix Collection builder example to be well-behaved with proper buffer allocation (#47994)
* Initial plan * Initial analysis and problem verification Co-authored-by: BillWagner <[email protected]> * Fix LineBuffer to be well-behaved collection Co-authored-by: BillWagner <[email protected]> * Update docs/csharp/language-reference/operators/snippets/shared/CollectionExpressionExamples.cs * Fix LineBuffer buffer allocation to use exact size needed Co-authored-by: BillWagner <[email protected]> * Update docs/csharp/language-reference/operators/snippets/shared/operators.csproj --------- Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: BillWagner <[email protected]> Co-authored-by: Bill Wagner <[email protected]>
1 parent ea8459a commit d368735

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

docs/csharp/language-reference/operators/snippets/shared/CollectionExpressionExamples.cs

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,40 @@
99
// <BufferDeclaration>
1010
public class LineBuffer : IEnumerable<char>
1111
{
12-
private readonly char[] _buffer = new char[80];
12+
private readonly char[] _buffer;
13+
private readonly int _count;
1314

1415
public LineBuffer(ReadOnlySpan<char> buffer)
1516
{
16-
int number = (_buffer.Length < buffer.Length) ? _buffer.Length : buffer.Length;
17-
for (int i = 0; i < number; i++)
17+
_buffer = new char[buffer.Length];
18+
_count = buffer.Length;
19+
for (int i = 0; i < _count; i++)
1820
{
1921
_buffer[i] = buffer[i];
2022
}
2123
}
2224

23-
public IEnumerator<char> GetEnumerator() => _buffer.AsEnumerable<char>().GetEnumerator();
24-
IEnumerator IEnumerable.GetEnumerator() => _buffer.GetEnumerator();
25+
public int Count => _count;
26+
27+
public char this[int index]
28+
{
29+
get
30+
{
31+
if (index >= _count)
32+
throw new IndexOutOfRangeException();
33+
return _buffer[index];
34+
}
35+
}
36+
37+
public IEnumerator<char> GetEnumerator()
38+
{
39+
for (int i = 0; i < _count; i++)
40+
{
41+
yield return _buffer[i];
42+
}
43+
}
44+
45+
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
2546

2647
// etc
2748
}

0 commit comments

Comments
 (0)