An array of several C # types (including other arrays)

Is there a way to have an array of several 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 is the right way to do this?

+5
source share
2 answers

The problem is that you cannot initialize the internal array this way. An array initializer can only be used in a variable or field initializer. As stated in your error:

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

You must explicitly initialize nested arrays. Do it like this 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 about Array Initializers

Your syntax will work if you define a two-dimensional array:

 object[,] x = { {"3"}, { 1 }, { 2 } }; 
+7
source

object[] x = {1,"G",2.3, 2,'H', {2} }; was wrong and you can use

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

+4
source

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


All Articles