Link to home
Start Free TrialLog in
Avatar of Unimatrix_001
Unimatrix_001Flag for United Kingdom of Great Britain and Northern Ireland

asked on

Compile-time casting

Hi,

I'm creating a class that will wrap around a Collections.Generic.List object so that I don't have to keep writing the same wrapper functions in all classes that use a List and can just make the variable public. While the code I've got below works, it means that the returned object from the getItem method will always need casting - kind of ruins the point a bit as that just creates as much code. Is there something I can do, maybe some sort of compile trickery to allow the getItem method return the type that it natively is? I've also unsuccessfully tried changing the declaration of List so that the type can be defined also in hopes of making it easier... No such luck.

Any help would be nice.

Thanks,
Uni.
Public Class CList
    Private localList As List(Of Object)
    Public Function getItem(ByVal aIndex As Integer) As Object
        getItem = localList.Item(aIndex)
    End Function
End Class

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of xtravagan
xtravagan

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of xtravagan
xtravagan

Why are you making a wrapper in the first place?
Avatar of Unimatrix_001

ASKER

Ooh! :D I wasn't aware .net has generics...

>>Why are you making a wrapper in the first place?
Because with the above I can make any variables of the type CList public without worrying about calling wrong methods and it keeps certain functions like adding an item with certain duplication properties constant without me having to constantly write them out.
Excellent - thank you. :)
If you work with generics, you do not need casting. See the following updated definition of your code:

Public Class CList(Of T)    Private localList As New List(Of T)    Public Function addItem(ByVal item As T) As T        localList.Add(item)    End Function    Public Function getItem(ByVal aIndex As Integer) As T        getItem = localList.Item(aIndex)    End FunctionEnd Class
When you call your code, you can call it like this:

Dim cl As New CList(Of String)cl.addItem("my string")Dim x As String = cl.getItem(0)
The reason this works without casting is because you use generics. And when you use generics, you do not need to add "Of Type" all the time. This technique is called Type Inference and is a new feature of .NET 3.5.

-- Abel --


ah, while typing, the question was commented, re-commented, and awarded... LOL. Have fun coding ;-)

> Ooh! :D I wasn't aware .net has generics...

interesting, you were using it in your statement "Of Object".
Hm... I think I'm going to have to get myself a nice book on VB.Net 3.5...
>>ah, while typing, the question was commented, re-commented, and awarded... LOL. Have fun coding ;-)
There'll be more coming up from me I'm sure. ;)