Doubt regarding arraylists

sudhanshu22

Member
Joined
Nov 8, 2006
Messages
20
Programming Experience
Beginner
Hi all,
can an arraylist contain objects of variety of classes. If yes,then when we want to extract an object from this arraylist, how do we come to know of its type ?

Thanks,
Sudhanshu
 
Yes, lingsn is correct. You can add anything to an arraylist as it boxes everything as an object. But if you want to know the system.type then you should use GetType as TypeOf will return true if the object is descended from the type you checked for. There is a difference between TypeOf and GetType, check them out. Secondly, i can't understand why you would want create an arraylist then put loads of different types into it. We should be heading toward TypeSafe'Ness in VB.Net hence the introduction of generics.
 
To reinforce vis' last point you shouldnt put all kinds of objects in a list..

Either make one object from which they can all descend (like imagine youre making the UNDO list of a paint program, all your elements in your undo list should be a Shape object maybe) or use separate lists.

The whole idea of polymorphism is that you dont waste time figuring out what something is with if type = something then do this, else do that etc

You simply have all the objects decend from a common parent and overload the implementation to do something different


Picture in your mind a list of things in your paint program.. You want to provide a facility to make everything on the screen attract attention to itself. All the drawn elements on screen are types of shape so they descend from Shape. It is decided that triangles will jump up and down, squares wobble left and right and circles will change colour
In your shape class you make a abstract method called DrawAttentionToYourself()

In the subclasses of Square, Triangle and Circle, you implement this abstract method in a different way

Now when you go over your list you treat everything as a shape and tell everything to draw attention to itself:

VB.NET:
Dim myShapesList as New System.Collections.Generic.List(Of Shape)
...
 
For Each s as Shape in myShapes
  s.DrawAttentionToYourself()
Next s

we do NOT do this:

VB.NET:
For Each s as Shape in myShapes
  If TypeOf(s) is Square Then
    DirectCast(s, Square).WobbleLeftAndRight()
  Else If TypeOf(s) is Triangle Then
    DIrectCast(s, Triangle).JumpUpAndDown()
  Else If ...
 
  .......
 
Next s

Hope this helps!

Oh, and there was a brief mention of generics by vis and I.. dont use ArrayList, use System.Collections.Generic.List(Of T) instead

Tell the list what type of object your putting in and you dont have to do any casting when you get it out.. further reinforcing the "unified type of object in a list" idea
 
Back
Top