Initializing c# array with new vs. initializing with literal

前端 未结 5 1631
时光说笑
时光说笑 2020-12-31 20:17

Simple Short Question What exactly is the difference between

int[] intarray = new int[2]{1,2};

and

int[] intarray2 = {4,5,         


        
5条回答
  •  星月不相逢
    2020-12-31 20:40

    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.

提交回复
热议问题