How to add different types of objects in a single array in C#?
C# has an ArrayList that allows you to mix types within an array, or you can use an object array, object[]:
var sr = new ArrayList() { 1, 2, "foo", 3.0 };
var sr2 = new object[] { 1, 2, "foo", 3.0 };
You can write an abstract base class called GameObject, and make all gameObject Inherit it.
Edit:
public abstract class GameObject
{
public GameObject();
}
public class TileStuff : GameObject
{
public TileStuff()
{
}
}
public class MoreTileStuff : GameObject
{
public MoreTileStuff()
{
}
}
public class Game
{
static void Main(string[] args)
{
GameObject[] arr = new GameObject[2];
arr[0] = new TileStuff();
arr[1] = new MoreTileStuff();
}
}
you can use an object
array. strings
, int
, bool
, and classes
are all considered objects, but do realize that each object doesn't preserve what it once was, so you need to know that an object is actually a string, or a certain class. Then you can just cast the object into that class/data type.
Example:
List<object> stuff = new List<object>();
stuff.add("test");
stuff.add(35);
Console.WriteLine((string)stuff[0]);
Console.WriteLine((int)stuff[1]);
Though, C# is a strongly typed language, so I would recommend you embrace the language's differences. Maybe you should look at how you can refactor your engine to use strong typing, or look into other means to share the different classes, etc. I personally love the way C# does this, saves me a lot of time from having to worry about data types, etc. because C# will throw any casting (changing one data type to another) errors I have in my code before runtime.
Also, encase you didn't know, xna is C#'s game framework (didn't have it as a tag, so I assume you aren't using it).
Very simple—create an array of Object class and assign anything to the array.
Object[] ArrayOfObjects = new Object[] {1,"3"}