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

php weird file_exists bug

php file-exists

Has anyone got any idea to why doesn't the following work ?

Quick dialog using onclick search view in android

android android-layout android-intent android-emulator

I am looking for a QuickAction dialog using onclick search view. Here is image showing what I am looking for: makes page scroll up


i'm using a popup and when i click it the page automatically goes up, how do i prevent this? i tried 'top:auto' it doesnt work here is my code

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.