LucasGH LucasGH - 2 years ago 93
C# Question

Array of multiple types C# (including other arrays)

Is there a way to have an array of multiple types in c#, including other arrays?
Apparently I can do this:

object[] x = {1,"G",2.3, 2,'H'};


but not this:

object[] x = {1,"G",2.3, 2,'H', {2} };


What's the proper way to do it?

Answer Source

Problem is that that you cannot initialize the inner array this way. The array initalizer can only be used in a variable or field initializer. As your error states:

Array initializer can only be used in a variable or field initializer. Try using a new expression insead

You must explicitly initialize the nested arrays. Do it this way and it works:

object[] x = { 1, "G", 2.3, 2, 'H', new int[]{ 2 } };
// Or a bit cleaner
object[] x = { 1, "G", 2.3, 2, 'H', new []{ 2 } };

Read more on Array Initializers

Your syntax would work if you'd define a 2 dimensional array:

object[,] x = { {"3"}, { 1 }, { 2 } };
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download