3

I want to inizialize a new int array.

What are the advantages of:

var myNewArray = new int[]{};

And:

var myNewArray = new int[0];

Which one should I prefer over the other, or is it just a matter of code-style?

Mafii
  • 7,227
  • 1
  • 35
  • 55
  • 1
    Look here: http://stackoverflow.com/questions/5678216/all-possible-c-sharp-array-initialization-syntaxes – Bartosz May 18 '17 at 08:05
  • @Bartosz thanks for the link. However, this is about initializing an array with items. I specifically wan't an empty array. – Mafii May 18 '17 at 08:07
  • 1
    No difference. But starting with NET4.6, the preferred way is to use [`Array.Empty()`](https://msdn.microsoft.com/en-us/library/dn906179(v=vs.110).aspx) which returns a singleton instance. – Ivan Stoev May 18 '17 at 08:11
  • 1
    @IvanStoev thanks a lot! I knew of Enumerable.Empty but somehow overlooked Array.Empty. – Mafii May 18 '17 at 08:12

1 Answers1

10

There is no difference. Both produce the same IL:

IL_0000:  nop         
IL_0001:  ldc.i4.0    
IL_0002:  newarr      System.Int32
IL_0007:  stloc.0     // myNewArray
IL_0008:  ret