Is it possible, to do something like that:
ArrayList arl = new ArrayList();
arl.Add(1);
arl.Add("test");
int[,] tab = new int[4, 4];
init(tab);
arl.Add(tab);
Is it possible to contain objects of various types (Like in JavaScript or Lua)? (C#)
Yes it is possible. ArrayList stores a collection of the type object meaning you can insert any .NET type.
You should really use List<T>. For example:
List<int> listIntegers = new List<int>();
listIntegers.Add(1);
You could also use List<object> however you will have to unbox all of the items in the list. Which potentially may incur performance issues.
You can have diffent types in a ArrayList
try this:
var ary = new ArrayList();
ary.Add("some string");
ary.Add(23.4);
ary.Add(new StringBuilder());
ary.Add("some other string");
You can then query it like this:
string[] strings = ary.OfType<string>();
StringBuilder[] stringBuilders = ary.OfType<StringBuilder>();
As for your question, yes ArrayList can contain various object types.
It is generally recommended by Microsoft to use List<T> instead, to prevent the need of boxing and unboxing to Type object when using the same types.
If you have a recurring pattern of types it might be more helpful (and faster) to define a custom class:
protected class arl_items
{
public string item1 {get; set;};
public int item2 {get; set;};
public int[4,4] item3 {get; set;};
}
and then go:
List<arl_items> arl = new List<arl_items>();
But if there is no pattern to your value-types you can as well use ArrayList, because creating List<object> would be meaningless, as they are the same.
Just btw. i prefer using List<object> over ArrayList, but that is only my personal preference
List<object> here. I would downvote your answer but I am not sure if you are saying an ArrayList and List<object> are essentially identical (which, they are), or you're saying to use a List<object> instead of an ArrayList (which is pointless).Yes it can since it does not do any type checking, it can sometimes be faster than a List<T> when working with reference types, though it is generally not recommended to use it when you have a perfectly fine type safe alternative.
Any type that inherits from object can be stored in an ArrayList. Whenever you access an item in an ArrayList you must be careful to cast it to the correct type or else you will get a compiler error.
I believe ArrayList is an old relic from the days before generic types in .Net
List<int> is significantly faster than adding to an ArrayList.ArrayList always performs faster than a List<class>.. is that not what you meant?
ArrayListcontains objects