C++ arrays VS C# arrays

Alex

New member
Joined
Jul 31, 2020
Messages
2
Programming Experience
Beginner
Hello! I'll go straight to the point.

I am coming from C++ and currently migrating to C# due to Unity's needs. Therefore, I have a question about arrays:

E. G. : int[] money = new int[10];

Why do we need to use a keyword - "new" and then declare, the size of the array? (i guess). In C++, I understood at first the declaration - e.g. : int ar[10];

In C#, why can't we use the " int[10] " first? Like, int[10] money.

Thanks, appreciate the effort if you take time to answer!
 
Recall that in C++, you could also do int *arr = new int[10];. This is what C# matches.

Part of C#'s "safety" is that it only puts value types on the stack. By it's nature, an array is more of a reference type, rather than a value type. (I'll leave aside why the syntax for value types in C# also require using new.)
 
It's not really about pointers. .NET references are sort of tarted-up pointers but the syntax is the same for value types and reference types. In C#, you declare a variable by specifying the type and then the name, then you can optionally initialise the variable you just declared. That's the rule in C# for variables and that's what you do. In this case, the type is int[] and the name is money so you need to specify both those things. You can then assign to that variable to initialise it. The initialising expression must evaluate to an object of the type of the variable. That might be a another variable, a property, a method call or a newly created object. You're using the last option in this case.

Note that, if you initialise a variable when you declare it, you can omit the explicit type and allow it to be inferred from the initialising expression, if you want the same type. That means using var instead of an explicit type. That exists specifically for LINQ queries that produce anonymous types but many people use it by default, myself included. It tends to make code a bit neater.
 
Back
Top Bottom