Search code examples
c#arrays.netinitialization

Initialization of only few values of c# array?


I am trying to write a program in which, I want to initialize 4 starting values of an array, while the other 16 will be entered manually from the console.

For this I have written the following code:

int[] intArray = new int[20] { 20, 22, 23, 0 }; 

But I am getting the following exception: "An array initializer of '20' is expected"

I know that it can be done by this syntax :

int[] intArray = new int[20];
intArray[0] = 20;
intArray[1] = 22;
intArray[2] = 23;
intArray[3] = 0;

I would like to know if this can be achieved in one line.


Solution

  • If you're going to be needing this frequently, you could create your own extension method to populate the values in an existing array:

    int[] intArray = new int[20].Populate(20, 22, 23, 0); 
    

    Sample implementation:

    public static class ListExtensions
    {
        public static TList Populate<TList, TElement>(this TList list, params TElement[] values)
            where TList : IList<TElement>
        {
            // TODO: argument validation
    
            for (int i = 0; i < values.Length; i++)
                list[i] = values[i];
    
            return list;
        }
    }