How does this compile? WITH#

object obj = new object[] { new object(), new object() };

How does this compile? This seems confusing.

It seems like it should be

object[] obj = new object[] { new object(), new object() };

or

object[] obj = { new object(), new object() };
+3
source share
5 answers

It compiles because an “object” can be anything, so it can be a reference to an array of an object. The code below, using strings to make the difference a little clearer, can help. So:

List<string> myStrings = new List<string>() { "aa", "bb" };
// Now we have an array of strings, albeit an empty one
string[] myStringsArray = myStrings.ToArray();
// Still a reference to myStringsArray, just held in the form of an object
object stillMyStringsArray = (object)myStringsArray;

// Get another array of strings and hold in the form of an object
string[] anotherArray = myStrings.ToArray();
object anotherArrayAsObject = (object)anotherArray;

// Store both our objects in an array of object, in the form of an object
object myStringArrays = new object[] { stillMyStringsArray, anotherArrayAsObject };

// Convert myStringArrays object back to an array of object and take the first item in the array
object myOriginalStringsArrayAsObject = ((object[])myStringArrays)[0];
// Conver that first array item back into an array of strings
string[] myOriginalStringsArray = (string[])myOriginalStringsArrayAsObject;

Essentially, an object can always be a reference to anything, even an array of objects. The object does not care what is placed in it, so at the very end of the code we have an array of strings. Run this code in Visual Studio, drop some breakpoints and follow through it. It, I hope, will help you understand why the code you specified is valid =)

+3

- . , .

+6

object obj = new object[] { ...}

object[], , , object.

+2

obj = ... object can refer to a collection here. He did not say that the difference in the use of the “object” here refers to the same type of object.

+1
source

An array of objects is an object, but it is really strange.

+1
source

Source: https://habr.com/ru/post/1734526/


All Articles