tags:

views:

694

answers:

1

I'm still learing VB.NET and usually I just google my questions, but this time I really don't know what to look for so I'll try here.

Trying to write a function that takes the cache key as a parameter and returns the cached object. No problems there, but I can't figure out how to pass the type into the function to use with TryCast, so that I don't have to do that with the returned result.

Here is my function so far, the ??? is to be replaced with the type that is passed into the function somehow.

Public Function GetCache(ByVal tag As String) As Object
    Dim obj As Object = Nothing
    Dim curCache As Object = TryCast(System.Web.HttpContext.Current.Cache(tag), ???)
    If Not IsNothing(curCache) Then
        Return curCache
    Else
        Return Nothing
    End If
End Function

Am I doing this completely wrong or am I just missing something?

A: 

Use a generic:

Public Function GetCache(Of T)(ByVal tag As String) As T
    Return CType(System.Web.HttpContext.Current.Cache(tag), T)
End Function

update:
Edited to use CType, because trycast only works with reference types. However, this could throw an exception if the cast fails. You can either handle the exception, check the type before making the cast, or limit your code to reference types like this:

Public Function GetCache(Of T As Class)(ByVal tag As String) As T
    Return TryCast(System.Web.HttpContext.Current.Cache(tag), T)
End Function
Joel Coehoorn
Thanks! But I actually tried that and it worked with DirectCast but not with TryCast, says 'TryCast' operands must be class-constrained type parameter, but 'T' has no class constaint.
Cyrodor
DirectCast will throw an exception if the types don't line up.
Joel Coehoorn
Sorry, I see now that you replaced TryCast with CType, that will cast an exception if it fails just like DirectCast if I'm not wrong? But maybe I should just avoid TryCast in this case.
Cyrodor
Yes, both will cause an exception. However, CType is more forgiving when you're not absolutely sure of the expected type.
Joel Coehoorn