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

Viewed 102223

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.

11 Answers

In C# 4 and later you can also use dynamic type.

dynamic[] inputArray = new dynamic[] { 0, 1, 2, "as", 0.2, 4, "t" };

Official docu

You can mix specific types doing the following:

(string, int)[] Cats = { ("Tom", 20), ("Fluffy", 30), ("Harry", 40), ("Fur Ball", 40) };
            
            foreach (var cat in Cats)
            {
                Console.WriteLine(string.Join(", ", cat));
            }

You have to declare your array with the datatype object:

object[] myArray = { };

myArray[0] = false;
myArray[1] = 1;
myArray[2] = "test";

You can use an array of object class and all it possible to add different types of object in array.

object[] array = new object[3];
array[0] = 1;
array[1] = "string";
array[3] = 183.54;
Related