views:

69

answers:

1

Given an array of strings, how do I create another array that has another entry inserted at initialisation time?

Eg. I want to do something like this:

var newArrayOfStrings = new string[] { "inserted entry", anotherArrayOfStrings }

(I know I can do this by getting a count and then copying; but I think it should be possible to do this at initialisation time.)

+3  A: 

No, there's no special syntax for doing that. You'll need to do the copying in one way or another:

var newArrayOfStrings = 
        new[] { "inserted entry" }.Concat(anotherArrayOfStrings).ToArray();

Performance-wise, this can be slower than Array.Copy but the syntax is cleaner.

Mehrdad Afshari
Thanks for your suggestion. Very useful.
Neil Pullinger