I'm not sure what was the question intent, but if you want to avoid array allocation with String.Split
method, you should use a custom code as suggested by @DonBoitnott :
var buffer = new string[3];
string testValue = "foo1;foo2;foo3;foo4;";
int count = Split(testValue, ';', buffer);
Debug.Assert(count == 3);
Debug.Assert(buffer[0] == "foo1" && buffer[1] == "foo2" && buffer[2] == "foo3;foo4;");
static int Split(string value, char separator, string[] buffer)
{
if (value == null)
return 0;
if (buffer == null || buffer.Length == 0)
throw new ArgumentNullException("buffer"); // or nameof(buffer) with c# 6 / .NET 4.6
const int indexNotFound = -1;
int bufferLength = buffer.Length;
int startIndex = 0;
int index;
int nextBufferIndex = 0;
while ((index = value.IndexOf(separator, startIndex)) != indexNotFound)
{
if (++nextBufferIndex == bufferLength)
{
buffer[nextBufferIndex-1] = value.Substring(startIndex);
break;
}
else
{
buffer[nextBufferIndex-1] = value.Substring(startIndex, index - startIndex);
startIndex = index + 1;
}
}
if (nextBufferIndex<bufferLength && value.Length >= startIndex)
buffer[nextBufferIndex++] = value.Substring(startIndex);
return nextBufferIndex;
}
Note that each string in the pre-allocated array is a new string allocation (String.Substring
allocates a new string).