-1

Which of the following execute faster and use the least amount of memory:

var array = new string[5];

or

string[] array = new string[5];

Also, what are the differences between these statements?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
BorHunter
  • 893
  • 3
  • 18
  • 44

3 Answers3

4

The compiler sees them as the same thing. Here's some IL from LINQPad to show that:

var array = new string[5];

IL:

IL_0001:  ldc.i4.5    
IL_0002:  newarr      System.String
IL_0007:  stloc.0     // array

and for string[] array = new string[5];

IL_0001:  ldc.i4.5    
IL_0002:  newarr      System.String
IL_0007:  stloc.0     // array

In the first example, the var keyword lets the compiler infer the type of array. The compiler sees it as an array of strings so the resulting IL code for both examples are exactly the same.

pcnThird
  • 2,362
  • 2
  • 19
  • 33
2

It will be compiled to exactly same IL code. Type of array variable will be inferred from usage, and compiler will generate variable of string[] type in first case.

Just read what MSDN tells about var (C# Reference):

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; // implicitly typed

int i = 10; //explicitly typed

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
1

There is no difference.First one is implicit type definition and second is explicit type definition.There is nothing about memory efficiency here

Selman Genç
  • 100,147
  • 13
  • 119
  • 184