chris
chris

Reputation: 37460

asp.net - passing generic lists

I have a utility class that takes a generic list as a parameter.

Code looks like:

Function DoStuff(collection as Object, elt as Object)
   ...
   collection.Add(elt)
   ...
End Function

This is called with:

DoStuff( List(Of Foo), new Foo() )
DoStuff( List(Of Bar), new Bar() )

There are about a dozen different types.

Currently, passing as Object results in a Late bound resolution warning, although it runs fine.

I've tried different ways to pass in collection and elt (Foo and Bar both extend a base class) but can't seem to figure out the "proper" way to do it.

Ideas?

Upvotes: 3

Views: 5141

Answers (3)

chyne
chyne

Reputation: 667

The answers by womp and Qua are I think the correct ones, however if your 12 types all inherit from some common base class (as your original question suggests) you can write the method such that it works with your types, and only your types as such:

Public Sub DoStuff(Of T As YourBaseClass)(collection As List(Of T), elt As T)
    ...
    collection.Add(elt)
    ...
End Sub

This way the method works only for types which inherit from YourBaseClass.

Upvotes: 4

womp
womp

Reputation: 116977

I think you're looking for something like this.

Public Sub DoStuff(Of T)(collection As List(Of T), elt As T)
    ...
    collection.Add(elt)
    ...
End Function

Upvotes: 7

Kasper Holdum
Kasper Holdum

Reputation: 13363

You should always strive to built/use strongly typed code. Imagine what would happen if an integer was passed as the collection object - You would have to manually check for the type of the variable. Even worse though, the user of your method would have to look up in the documentation what kind of object your method required as it's first parameter.

You should go by the approach suggested by womp, or even better you should make your parameter require an object that extends the generic collection interface, ICollection(Of T):

Public Function DoStuff(Of T)(collection As ICollection(Of T), elt As T) As stuff
...
collection.Add(elt)
...
End Function

since this would allow the user of the method to pass not only lists, but also all other classes that inheritage the ICollection(Of T) interface (synchronizedCollection, HashSet, LinkedList, or custom classes ect.) which is really the power of OO programming.

Upvotes: 1

Related Questions