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?
No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.
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.
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.
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.
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 } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With