I am still struggling with understanding the creation of objects.
For example.
int[] x = {4,5,6};
int[] y = new int[x.Length];

Why is it that for the first array, we can initialize it without the use of the new keyword yet in the second line, we need the new keyword?
Whats the difference?
Thanks so much.

Dani AI

Generated

Short answer: the brace-only initializer is a declaration-only shorthand; the compiler expands it into an array creation. was thinking in the right direction and was right that filling an array of objects requires you to create each object instance.

Why this exists: arrays in C# are reference types. The brace form you saw is syntax sugar that the compiler accepts only when you declare the variable; behind the scenes it becomes a new array with the listed elements. Using an explicit creation like new T[n] allocates an array of that length and sets every element to default(T) (0 for numbers, false for bool, null for reference types). To put actual objects into an array you must assign instances to each slot.

Examples of the common forms:

string[] names = { "Alice", "Bob", "Carol" };
int[] scores = new int[] { 10, 20, 30 };
MyThing[] things = new MyThing[3];
for (int i = 0; i < things.Length; i++)
{
    things[i] = new MyThing(i);
}

A couple of practical tips: you cannot use the brace-only form on a later assignment (for example arr = { ... }; is invalid). Use new[] { ... } with var for implicit typing when convenient. If you need resizable collections or easier construction patterns, prefer List<T> and its collection initializers or LINQ to create populated sequences. For further reading, official C# docs and a focused book such as "C# in Depth" cover these forms and the underlying rules in detail.

Recommended Answers

All 3 Replies

Member Avatar for Member #46692

Do you have a book to refer back to.

I think I got it. One creates an instance and fills it.
The other creates it but leaves it empty and with a size. I guess if we are just going to create it, we need the extra step but if we initialize it and fill it, we can short circuit it.

Yep. Thats right. Its easy to initialize the array. It is sometimes a pain in the butt to fill it with objects though. You have to create a loop to intialize the individual values (or use the brackets for simple data types.) But you know all this now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.