4

In tutorials, I've been seeing that there are two ways to assign values to an array in C#.

First method is:

double[] values = {23.245, 14.22,12.00};

Second method is:

double[] values = new double[] {23.245, 14.22, 12.00};

I would appreciate it if someone explained to me the difference between the two.

Cheers.

Arnav Gaur
  • 117
  • 5
  • 1
    I disagree. The other one was asking for the need of the "new" keyword. I know what the new is for. I understand what new is for. I just wanted to know if there was any difference without using it. – Arnav Gaur Jul 06 '16 at 07:13
  • 1
    This link can be useful to: [All possible C# array initialization syntaxes](http://stackoverflow.com/questions/5678216/all-possible-c-sharp-array-initialization-syntaxes) – Purnima Naik Jul 06 '16 at 07:15
  • The answers on the duplicate cover this well: both forms are absolutely the same. – H H Jul 06 '16 at 07:24
  • why you mark an answer that is exactly the same with the answer in a question that you said different with yours? – Mark Jul 06 '16 at 07:26

2 Answers2

3

The first uses the concept of array initializers. It's a syntactic sugar. For further info, please have a look here.

Christos
  • 53,228
  • 8
  • 76
  • 108
1

Absolutely no difference...

IL_0000:  ldc.i4.3    
IL_0001:  newarr      System.Double
IL_0006:  dup         
IL_0007:  ldtoken     <PrivateImplementationDetails>.DBF4DA99AFD5E0399193CCEAA18D1DC95D64CC38
IL_000C:  call        System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray
IL_0011:  pop         
IL_0012:  ret         

That's what it will be compiled down to, using either statement

Aydin
  • 15,016
  • 4
  • 32
  • 42