C # Using the new []

I have a question about using new[] .

Imagine the following:

 Object.SomeProperty = new[] {"string1", "string2"}; 

Where SomeProperty expects an array of strings.

I know this piece of code will work. But I want to know what he is doing under the hood. Does new[] create an instance of the object class, and in SomeProperty it automatically convert it to a string object?

thanks

+6
new-operator c #
source share
5 answers

Well, there is still a bit of confusion.

The output that occurs has nothing to do with the Object.SomeProperty type, but it all depends on the types of expressions in the array initializer. In other words, you could do:

 object o = new[] { "string1", "string2" }; 

and o will still be a reference to a string array.

Basically, the compiler looks at this expression:

 new[] { A, B, C, D, ... } 

(where A, B, C, D, etc. are expressions) and tries to work out the right type of array to use. It considers types A, B, C, and D (etc.) as the type of an array element. Accepting this set of candidate types, he tries to find one to which all others can be implicitly converted. If there is no such one type, then the compiler will complain.

So for example:

 new[] { new Form(), new MemoryStream() } 

will not compile - neither MemoryStream nor Form will be converted to others. But:

 new[] { GetSomeIDisposable(), new MemoryStream() } 

will be considered as IDisposable[] , because there is an implicit conversion from MemoryStream to IDisposable . Similar:

 new[] { 0, 1, 3.5 } // double[] new[] { 1, 3, 100L } // long[] 
+16
source share

It is just syntactic sugar. The compiler will infer the type needed here and create code equivalent to the explicit construct:

 Object.SomeProperty = new string[] {"string1", "string2"}; 

There is no such thing as new[] that starts at run time.

+15
source share

This roughly translates to:

 string[] $temp = new string[2]; $temp[0] = "string1"; $temp[1] = "string2"; Object.SomeProperty = $temp; 

Interestingly, var x = new[] { "string1", "string2" }; also works, it can output x as string[] , but var x = { "string1", "string2" }; fails.

+3
source share

The compiler replaces:

 Object.SomeProperty = new[] {"string1", "string2"}; 

from:

 Object.SomeProperty = new string[] {"string1", "string2"}; 
+2
source share

I hope that from your answer you will not get confused between type substitution and output type here! I assume the Object.SomeProperty type is the string [], although due to covariance of the array it may be the object [] (note that this is not very good - see Eric Lippert 's Post on this topic!).

The compiler performs type inference using heuristics - it determines that the strings "string1" and "string2" have a type string, and therefore it effectively replaces your code: -

 Object.SomeProperty = new string[] {"string1", "string2"}; 

It's really that simple! All this was done at compile time, there was nothing at runtime.

+1
source share

All Articles