spinjector spinjector - 4 months ago 26
Vb.net Question

Convert or Cast from StringCollection to ObjectCollection?

I would like to populate a listbox with a list of installed printers in VB.net.

This works:

Dim printerList As System.Drawing.Printing.PrinterSettings.StringCollection
printerList = System.Drawing.Printing.PrinterSettings.InstalledPrinters

For Each printerName In printerList

This does not work:


...because of the following type-conversion error:

Public Sub AddRange (value As
System.Windows.Forms.ListBox.ObjectCollection)': Value of type
'System.Drawing.Printing.PrinterSettings.StringCollection' cannot be
converted to 'System.Windows.Forms.ListBox.ObjectCollection'.

Is it possible to directly cast one to the other for use in AddRange() as shown? Or is the loop the only (or most efficient) way?


Well, you're dealing with 2 collections that were created before the more modern generic lists and enumerables, so their use is less fluid.

In this case, the AddRange method accepts either another ObjectCollection instance (not your case), or an array of Objects. If you want to benefit from the latter, you'll need to transform the StringCollection instance to an array of Objects. Here is how this can be done:

ListBox1.Items.AddRange(printerList.Cast(Of Object)().ToArray())

That said, I would stick with your current For Each loop. It is very readable, and doesn't create an intermediate array. But, I doubt either choice will make much difference, so pick your favorite.