Collection/list problem

C

Clive Lumb

Hi,

I'm having a problem while adding objects to a collection. (VB.net 2005)
I am reading data in from a file to a temporary variable (eg MyClass) and
then adding it to a collection.
When I then enumerate the collection, all the entries are equal to the last
one added.
The same thing happens with lists and with a generic list(of type).
Obviously the collection or list is storing a reference to the variable,
rather than the values - hence all the items refer to the same variable.

I am probably missing something really basic - please be patient :)

Many TIA

example:

Public Class MyThing
name as String
Value as integer
end class

Dim MyClass as New MyThing
Dim MyCollection as New Collection

'open file
'do
' read in name, value
MyClass.name=NameFromFile
MyClass.value=ValueFromFile
MyCollection.Add(MyClass)
'loop to end of file
'close file
 
C

Clive Lumb

Yay! it works!
I would recommend reading once the language specification to clear out the
basics...
Unfortunately I have the French version which is dire, for example it says
that objects in a collection *should* not be of the same type (instead of
*need* not).
 
L

Lev Blaivas

Yay! it works!


Unfortunately I have the French version which is dire, for example it says
that objects in a collection *should* not be of the same type (instead of
*need* not).

Here is a great article about reference and value types;
http://www.ondotnet.com/lpt/a/2789
explains in detail the difference between value and reference types
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top