If I execute the following code in .Net Core 6, C# Version 10 ...
int[] arrInts = new int[] { };
string[] arrStrings = new string[] { };
Console.WriteLine($"arrInts.Length == {arrInts.Length}");
Console.WriteLine($"arrStrings.Length == {arrStrings.Length}");
arrInts.Append(13);
arrStrings.Append("13");
Console.WriteLine($"arrInts.Length == {arrInts.Length}");
Console.WriteLine($"arrStrings.Length == {arrStrings.Length}");
... the code executes, & length stays 0
after the .Append(...)
statements.
But if arrays in C# cannot be changed, then why does the method .Append(...)
exist on arrays?.. & what does it actually do when you call it?
Why does it not throw an error?...
Based on comments, I understand / know that I can do the following:
arrInts = arrInts.Append(13).ToArray<int>();
arrStrings = arrStrings.Append("13").ToArray<string>();
Console.WriteLine($"arrInts.Length == {arrInts.Length}");
Console.WriteLine($"arrStrings.Length == {arrStrings.Length}");
... because .Append(...)
comes from IEnumerable<TSource> Append<TSource>
But that seems counter-intuitive, no? .Append(...)
should actually 'append', no? One would think it would do the .ToArray
"under the hood", so that it "appends".?.
Or should the method have really been named: ToIEnumerableWithAppend
?