Possible Duplicate:
What is this new[] a shorthand for?
Is there any difference between
var strings = new string[] { "hello", "world" };
and
var strings2 = new[] { "hello", "world" };
In this case, no difference, as new[]
will infer the provided values type as string
.
See Implicitly typed arrays.
No difference.
The second one is a syntactic-sugar called "Implicitly typed arrays", and both the expressions return an array of strings.
When you don't specify the type of the array, it is inferred from the types of the elements used to initialize the array.
To allow the inference, the expression must satisfy the following condition:
Considering an implicitly typed array expression like this:
var arr = new []{ obj1, ... , objn }
and the set of all the types of the elements in the initialization being:
S = {T1, ..., Tn}
to allow the inference (i.e. no compiler error) it must be possible for all the types { T1, ... , Tn }
to be implicitly cast to one of the types in the set S
.
So, for example, given the following classes:
class Base { }
class Derived1 : Base { }
class Derived2 : Base { }
class Derived3
{
public static implicit operator Base(Derived3 m)
{ return null; }
}
This code compiles:
var arr = new []{ new Derived1(), new Derived2(), new Derived3(), new Base()};
while the following does not:
var arr = new []{ new Derived1(), new Derived2(), new Derived3() };
since in the first case all the 3 types can be implicitly cast to type Base
, and Base
type is inside the set S = { Derived1, Derived2, Derived3, Base }
, while in the second case all the types cannot be cast to one type in the set S = { Derived1, Derived2, Derived3 }
This feature has been introduced with C# 3.0 along with anonymous types and it makes instantiation of arrays of the latter easier.
For instance, this would be really hard to obtain without implicitly typed arrays:
var arrayOfAnonymous = new[] { new { A = 3, B = 4 }, new { A = 2, B = 5 } };
In this case, there is no difference. Because of hello
and world
are string
;
var strings2 = new[] { "hello", "world" };
creates a string[]
array which is the same with first one.
Second one is just called Implicitly Typed Arrays
If we go one step further, they have the same IL
code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With