Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add different types of objects in a single array in C#?

Tags:

arrays

c#

.net

I am planning to rewrite my Python Tile Engine in C#. It uses a list of all the game objects and renders them on the screen. My problem is that unlike in Python where you can add almost anything to an array (e.g x = ["jj" , 1, 2.3, 'G', foo]) you can add only one type of objects in a C# array (int[] x = {1,2,3};) . Are there any dynamic arrays (similar to the ArrayList() class) or something which allows you to pack different types into a single array? because all the game objects are individual classes.

like image 816
ApprenticeHacker Avatar asked Jun 26 '11 05:06

ApprenticeHacker


People also ask

How do I store different data types in one 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.

Can we add different data types in array?

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

How do you create an array with different data types?

You have to use the object array when you want to create an array of multiple data types in C#. By declaring the array as an Object you can have multiple data types. object[] requiredArray = new object[5];As System.

Can you have an array of different types in C?

Array in C are of two types; Single dimensional arrays and Multidimensional arrays. Single Dimensional Arrays: Single dimensional array or 1-D array is the simplest form of arrays that can be found in C.


1 Answers

Very simple—create an array of Object class and assign anything to the array.

Object[] ArrayOfObjects = new Object[] {1,"3"} 
like image 191
Nitesh Avatar answered Sep 24 '22 02:09

Nitesh