7

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?

2 Answers 2

8

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 } };
Sign up to request clarification or add additional context in comments.

Comments

4

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.