g1ji
g1ji

Reputation: 1129

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.

Upvotes: 0

Views: 412

Answers (5)

g1ji
g1ji

Reputation: 1129

I found jon skeet suggestion more useful.

new[] { 20, 22, 23, 0 }.Concat(Enumerable.Repeat(0, 16)).ToArray();

Upvotes: 0

TaW
TaW

Reputation: 54433

This works in two lines:

  int[] intArray = new int[20];
  new int[4] { 20, 22, 23, 0 }.CopyTo(intArray , 0);

Or even:

  int[] intArray = new int[20];
  new int[] { 20, 22, 23, 0 }.CopyTo(intArray , 0);

Note that the unnamed array goes out of scope right after the semicolon.. - I don't think it gets any simpler!

Upvotes: 0

Chris
Chris

Reputation: 5514

How about keeping it simple:

public static T[] CreateAndInitArray<T>( int len, T[] initialValues )
{
    var temp = new T[len];
    initialValues.CopyTo( temp, 0 );
    return temp;
}

Use:

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

The initialValues argument could be a params argument too, but that would easily be confusing considering the length argument. Personally I like the answer Douglas provided better, looks alot more logical.

Upvotes: 1

user2884232
user2884232

Reputation: 25

I think that you could do something like this:

    private static int[] getInput()
    {

        int[] array = { 20, 22, 23, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,    1, 1 };

        bool done = false;
        int current = 4;
        while (!done)
        {
            Console.WriteLine("Enter in a number to be added to the array");
            string input = Console.ReadLine();
            array[current] = Convert.ToInt32(input);
            current++;
            if (current==array.Length)
            {
                done = true;
            }
        }
        return array;
    }

Upvotes: -1

Douglas
Douglas

Reputation: 54887

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;
    }
}

Upvotes: 2

Related Questions