39

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.

1
  • 1
    Creating a new class is your wisest solution. Commented Mar 22, 2015 at 0:14

11 Answers 11

73

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

Object[] ArrayOfObjects = new Object[] {1,"3"}
Sign up to request clarification or add additional context in comments.

1 Comment

you mean like object[] x = {1,"G",2.3,'H'}; ? Will this work?
18

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).

8 Comments

@I'm using SFML .NET. I already knew C++/SFML so it was easier. And it is Cross-Platform and compatible with MONO.
Hm, good to know, xna is my personal favorite, but if cross platform is important to you, that would be a deal breaker.
Can u use xna without visual studio?
@mazzzzz: "but do realize that each object doesn't preserve what it once was". This is not exactly true. You can use this to determine the underlying data type: stuff[0].GetType().Name or .FullName.
I am a believer that you shouldn't try to use a language as if it were another. Languages are usually designed with a certain pragmatic system in mind. Python coders think through problems differently than those who use C#. I enjoy these differences; and recommend, at least initially, you embrace a new language's mindset, as it'll open up your problem solving skills. Working with strong type as an advantage instead of a nuisance is an example of this. As for the lists, you're right, but it's very easily translatable to primitive enumerables.
|
15

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();
    }
}

1 Comment

Better than Object
11

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 };

Comments

4

In c# we use an object[] array to store different types of data in each element location.

  object[] array1 = new object[5];
//
// - Put an empty object in the object array.
// - Put various object types in the array.
// - Put string literal in the array.
// - Put an integer constant in the array.
// - Put the null literal in the array.
//
array1[0] = new object();
array1[1] = new StringBuilder("Initialized");
array1[2] = "String literal";
array1[3] = 3;
array1[4] = null;

Comments

3

You can use object[] (an object array), but it would be more flexible to use List<object>. It satisfies your requirement that any kind of object can be added to it, and like an array, it can be accessed through a numeric index.

The advantage of using a List is you don't need to know how items it will hold when you create it. It can grow and shrink dynamically. Also, it has a richer API for manipulating the items it contains.

Comments

3

Here is how you can do it

Use List<object> (as everything is derived from object in C#):

var list = new List<object>();
list.Add(123);
list.Add("Hello World");

Also dynamic might work for you (and your python background)

var list = new List<dynamic>();
list.Add(123);
list.Add(new
{
    Name = "Lorem Ipsum"
});

If you wan't to use dynamic you really need to know what you're doing. Please read this MSDN article before you start.

But do you need it?

C# is a strongly-typed and very solid programming language. It is very flexible and great for building apps using object-oriented and functional paradigms. What you want to do may be acceptable for python, but looks pretty bad on C#. My recommendation is: use object oriented programming and try to build model for your problem. Never mix types together like you tried. One list is for a single data-type. Would you like to describe your problem in depth so that we can suggest you a better solution?

2 Comments

I ran some benchmarks with different list operations for both List<dynamic> and List<object> and the object list performs much better (both CPU and RAM) when it comes to reading and doing operations with the list items. There is no difference for the Add operation.
@Serj you're probably right. I haven't come across the scenario where this performance difference would be so critical. Most apps/websites run just fine even with heavy reflection these days.
2

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

Comments

0

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));
            }

1 Comment

This is not "mix"ing anything like the question asks; every element of Cats is of the same type: a ValueTuple consisting of a string field and an int field. Also, because you're passing a single value to the params object[] overload of string.Join() there's nothing to join, and so the output is the same as simply Console.WriteLine(cat);.
-1

You have to declare your array with the datatype object:

object[] myArray = { };

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

Comments

-1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.