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?
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?
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 string
s so the resulting IL code for both examples are exactly the same.
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
There is no difference.First one is implicit type definition and second is explicit type definition.There is nothing about memory efficiency here