I have a question about using new[].
Imagine this:
Object.SomeProperty = new[] {'string1', 'string2'};
Where SomeProperty expects an array of strings.
I know this code snippet will work. But i want to know what it does under the hood. Does new[] makes an instance of the class object and in SomeProperty it converts it automatically to a string object?
Thanks
Okay, there’s still a little bit of confusion here.
The inference that’s going on has nothing to with the type of Object.SomeProperty, but everything to do with the types of the expressions in the array initializer. In other words, you could do:
and o would still be a reference to a string array.
Basically, the compiler looks at an expression like this:
(where A, B, C, D etc are expressions) and tries to work out the correct array type to use. It only considers the types of A, B, C and D (etc) as the array element type. Taking this set of candidate types, it tries to find one which all the others can be implicitly converted to. If there’s not exactly one such type then the compiler will complain.
So for example:
will not compile – neither
MemoryStreamnorFormis convertible to the other. However:will be treated as an
IDisposable[]because there’s an implicit conversion fromMemoryStreamtoIDisposable. Likewise: