5

In C#, can I store multiple data types in an ArrayList? Like;

myArrayList.Add(false);
myArrayList.Add("abc");
myarrayList.Add(26);
myArrayList.Add(obj);

I know i can make a DataTable or a class for it.

But, please let me know: is this possible? And if so, what are it's De-merits of being a collection class?

2
  • 2
    Yes, it's possible (and it will work as typed up!) .. but it's also often a PITA to deal with "a bunch of objects" later. Static/strong typing is nice; use it - and to this I suggest using List<T> instead of [the old] ArrayList. Commented Oct 29, 2012 at 6:31
  • 1
    What is the use case you are considering here? Commented Oct 29, 2012 at 6:53

3 Answers 3

9

Yes you can store like this

ArrayList aa = new ArrayList();
aa.Add(false);
aa.Add(1);
aa.Add("Name");

ArrayList belongs to the days that C# didn't have generics. It's deprecated in favor of List. You shouldn't use ArrayList in new code that targets .NET >= 2.0 unless you have to interface with an old API that uses it.

ArrayList vs List<> in C#

Sign up to request clarification or add additional context in comments.

1 Comment

Another solution create generic list of anonymous type. Check this.
1

i guess List<object> help you.

Comments

0

Yes, you can store objects of different types in an ArrayList but, like pst mentioned, it's a pain to deal with them later.

If the values are related in some way you are probably better off writing a class to hold them. This will give you strong typing and the values will be named so someone else looking at the code will have a chance of understanding what's going on.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.