creating a ToString method for a Generic List

G

Guest

I'm sure this is something pretty trivial but can't seem to figure out how
to do it.

I'm using Generic Lists in quite a few places in my app and for some of them
want to be able to create a ToString method that would return a formatted
string array.

For example, I might have a simple class as follows:

Class Foo

Public ItemIndex as short
Public Description as string

End Class

There would be a List object containing instances of this class e.g.

Dim MyFoos as List (Of Foo)

now say for populating a drop-down list I want to display items in the
following format:

1 : Item A
2: Item B
3: Item C
etc.

I would like to be able to populate the dropdown list (ddl) using the
AddRange() method, so I'd need something like
ddl.Items.AddRange(MyFoos.ToString).

How would I implement this method? I've tried creating my own NumberedList
class which inherits from Generic.List but couldn't see how I could access
the list itself.

Thanks in advance
 
C

Chris

Richard said:
I'm sure this is something pretty trivial but can't seem to figure out how
to do it.

I'm using Generic Lists in quite a few places in my app and for some of them
want to be able to create a ToString method that would return a formatted
string array.

For example, I might have a simple class as follows:

Class Foo

Public ItemIndex as short
Public Description as string

End Class

There would be a List object containing instances of this class e.g.

Dim MyFoos as List (Of Foo)

now say for populating a drop-down list I want to display items in the
following format:

1 : Item A
2: Item B
3: Item C
etc.

I would like to be able to populate the dropdown list (ddl) using the
AddRange() method, so I'd need something like
ddl.Items.AddRange(MyFoos.ToString).

How would I implement this method? I've tried creating my own NumberedList
class which inherits from Generic.List but couldn't see how I could access
the list itself.

Thanks in advance

I could be very wrong about this as I haven't done it myself, but I
believe you need to add the ToString method in your Foo class, not the
list. The addrange will go through each item in your list and to do
ToString method on it.

Chris
 
G

Guest

Chris

Thanks a lot! Think i was making too much of it. By implementing a ToString
method on the class itself, I was then able to use the List's ToArray
method...

ddl.Items.AddRange(MyFoos.ToArray)

Cheers :)
 

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