How does Collections and List store objects of different types ? Is it Possible?

How does generic collections and List store objects of different types ? Is it Possible?

Because collections and List are a replacement for arraylist


The main advantage of generic collections is that you can specify the exact type you want to store in the collection and don't need boxing.

You have some options here:

  • You stick to the nongeneric collections in the System.Collections namespace which take object as a parameter.
  • You create a generic collection of type object. This is more or less the same as above, but you can use all the extension methods that exist for IEnumerable<T>.
  • You create a generic collection of a common interface, that all types you want to store, implement.

If you need to store various types, you need to declare your collection to be of a type that all the other types are compatible with.

So for example, to put both a MemoryStream and a FileStream in a list, you might have a List<Stream>:

List<Stream> streams = new List<Stream>();
streams.Add(new MemoryStream());
streams.Add(new FileStream(...));

For more disparate types, you may need to go as far as List<object>:

List<object> objects = new List<object>();
objects.Add("hello"); // A String
objects.Add(5); // An Int32
objects.Add(new Button());

Note that in this case, value type values will be boxed - whereas they wouldn't in a list of that specific value type.

To use any type-specific members of elements, you'd need to check that they were the right type and cast them, e.g. with is and a cast, or as:

string maybeString = objects[0] as string;
if (maybeString != null)
    Console.WriteLine("String of length {0}", maybeString.Length);

well, you need to make the list store the most common denominator; if you want to store anything, you need a List<object>() or perhaps List<IMyCommonInterface>().

However, in my experience, if you find yourself coding like this, you might want to reconsider your architecture.

Perhaps you could explain the solution you're trying to achieve ?

Need Your Help

limiting the view height of uitabbarviewcontroller ios7 without storyboard

objective-c ios7 uitabbarcontroller xcode5.0.1

I have a tableviewcontroller and on the respective rowclick of the tableviewcontroller i want to show the details of that respective rows detail content.

Dynamic width depending on sidebars in wordpress

php wordpress dynamic sidebar

im building wordpress theme and i created 4 sidebars to use on footer, now i need to have dynamic width of those 4 sidebars depending of how many of them are active.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.