Is it possible to put different datatypes in the same List<>?

  • Thread starter Thread starter JB
  • Start date Start date
J

JB

Hello

List<T> is said to be more powerful than ArrayLists but if you have
something like this:

List<int> mylst = new List<>;
myList.Add("Joe");
myList.Add(25);

the list doesn't seem to accept the name "Joe".

How do you get a List<> to accept different datatype if possible?

JB
 
JB said:
Hello

List<T> is said to be more powerful than ArrayLists but if you have
something like this:

List<int> mylst = new List<>;
myList.Add("Joe");
myList.Add(25);

the list doesn't seem to accept the name "Joe".

How do you get a List<> to accept different datatype if possible?

List<object> myList = new List<object>();
myList.Add("Joe");
myList.Add(25);
 
JB said:
List<T> is said to be more powerful than ArrayLists but if you have
something like this:

List<int> mylst = new List<>;
myList.Add("Joe");
myList.Add(25);

the list doesn't seem to accept the name "Joe".

How do you get a List<> to accept different datatype if possible?

The old ArrayList or List<object>.

But but but - maybe you should reconsider your object model - it
looks very weird. Maybe you want a List<Person> where Person
has Name and Age properties.

Arne
 
If you are using List<object> and adding value types to the list, you
are doing lot of boxing and un-boxing.
Arne already pointed out that "you should reconsider your object model "

Thanks & Regards,
Ashutosh
 
JB said:
Hello

List<T> is said to be more powerful than ArrayLists but if you have
something like this:

List<int> mylst = new List<>;
myList.Add("Joe");
myList.Add(25);

the list doesn't seem to accept the name "Joe".

How do you get a List<> to accept different datatype if possible?

JB

You use the most specific data type that is common for the data types
that you want to put in the list.

As mentioned in the thread, List<Object> works the same way as an
ArrayList. If you really need a list of object references, you should
rather use List<Object> than ArrayList. That way it's clear that you
actually indended to use that kind of list, and not that you just used
an ArrayList because you didn't know better.

In most cases, you should be able to find a common data type that is
more specific than Object. For example if you want to put instances of
System.Windows.Controls.Button and System.Windows.Controls.Label in the
same list, you can use a List<System.Windows.Controls.Control>.
 
Back
Top