Initializing c# array with new vs. initializing with literal
Simple Short Question What exactly is the dif开发者_如何学编程ference between
int[] intarray = new int[2]{1,2};
and
int[] intarray2 = {4,5,6};
Like what does the "new" do exactly? and do you really need it?
Im guessing it just allocates memory.....or something? Sorry im completely new to C# and have questions as I go about learning it.
The second is array initializer syntax. It's just syntactic sugar. Both initialize new array instances with their respective values, the first being more explicit (you repeat that it is an integer array of two elements on the right hand side which is pretty obvious from what follows so the compiler is capable of inferring this information).
So the following are equivalent:
int[] array = new int[2] { 1, 2 };
and:
int[] array = { 1, 2 };
and:
var array = new[] { 1, 2 };
In all cases we are initializing an array of two integers. Personally I prefer the last syntax.
Arrays are reference types and are allocated using the C# new
keyword as are other reference types.
One of your array syntaxes is simply a shorter syntax also recognized by the C# compiler - (there are other variations on it too) Both your examples allocate (new) and initialize {elements} for an array instance:
The first version explicitly states the size of the array.
int[] intarray = new int[2]{1,2};
The second version lets the C# compiler infer the size of the array by # of elements in the initialization list.
int[] intarray2 = {4,5,6};
In general the C# compiler recognizes specialized syntax for declaring and initializing C# native arrays masking the fact the underlying System.Array
class is being used.
int[] intarray2 = {4,5,6};
is exactly the same than:
int[] intarray2 = new int[] {4, 5, 6};
is just a shorter (abbreviated) form of coding, in fact the compiler WILL allocate the memory the same qty of memory for the array, the first one is not explicitly write the "new", just like when you assign an integer to a double variable, you can write the cast or not (because is a safe cast), and will produce the same effect. example:
int i = 12;
double d = i;
the same as:
int i = 12;
double d = (double)i;
This is a syntactic sugar.
There is no difference between them; they will compile to identical IL.
However, the array initializier can only be used to initialize array fields or properties.
http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx
Acc. to this, new will just call the default constructor.
int i=new int();
OR
int i=0;
are same.
精彩评论