Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of multiple types C# (including other arrays)

Tags:

arrays

c#

types

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?

like image 984
LucasGH Avatar asked Aug 16 '17 09:08

LucasGH


People also ask

Can an array have multiple data types in C?

No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.

Can you store different types in an array in C?

Yes we can store different/mixed types in a single array by using following two methods: Method 1: using Object array because all types in . net inherit from object type Ex: object[] array=new object[2];array[0]=102;array[1]="csharp";Method 2: Alternatively we can use ArrayList class present in System.

How do you create an array of different data types in C++?

To create an array, you should state its name, data type, and the number of designated elements within square brackets: The type can be int, float, char, or string data. The array_name corresponds to the name of the array you're about to create. The array_size must be bigger than zero.

Can arrays be double in C?

In case it isn't clear, your array cannot be of double length. It's undefined behavior. This is because a double is not an integer, but a rational number that could be an integer.


1 Answers

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 } };
like image 198
Gilad Green Avatar answered Sep 25 '22 05:09

Gilad Green