Search code examples
c#collections

Heterogeneous and homogeneous collection of objects in C#


With a little bit of definition, can someone please give us code-examples of the both collection types for understanding purposes.


Solution

  • In heterogeneous collection, you can add any type of data into collection for example,

    ArrayList a = new ArrayList();
    a.Add(1); // integer 
    a.Add("any string"); // any string 
    a.Add(new { any = "Test Data" }); //any object
    
    • For a heterogeneous collection of objects, use the List<Object> (in C#) or List(Of Object) (in Visual Basic) type.

    • For a homogeneous collection of objects, use the List<T> class.

      e.g. List<int> lst = new List<int> { 1,2,3,4 };

      above, you can't have multiple data-types in same collection i.e. { 1,2,3,"a" }

    see https://msdn.microsoft.com/en-us/library/system.collections.arraylist(v=vs.110).aspx for more