Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this compile? c#

Tags:

c#

compilation

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

How does this compile? It seems confusing.

Seems it should either be

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

or

object[] obj = { new object(), new object() };
like image 284
maxp Avatar asked Apr 23 '26 11:04

maxp


2 Answers

object is the base for everything. Anything can be assigned to a variable of type object.

like image 174
kyoryu Avatar answered Apr 26 '26 02:04

kyoryu


It compiles because an "object" can be anything, therefore it can be a reference to an array of object. The code below using strings to make the distinction a little clearer, might 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 object. Object doesn't care what is put in it, so by the very end of the code there, we've got a string array back. Run that code up in Visual Studio, drop a few breakpoints in and follow it through. It'll hopefully help you make sense of why the code you specified is valid =)

like image 31
Rob Avatar answered Apr 26 '26 02:04

Rob