I've got this function:
Public Shared Function GetQueryStringValue(Of T As Structure)(ByVal queryStringVariable As String) As T
Dim queryStringObject As Nullable(Of T) = Nothing
If queryStringVariable <> Nothing Then
If HttpContext.Current.Request.QueryString(queryStringVariable) IsNot Nothing Then
queryStringObject = DirectCast(HttpContext.Current.Request.QueryString(queryStringVariable), T)
End If
End If
Return queryStringObject
End Function
Which I was hoping to call like this:
Dim userId As Integer = SessionUtil.GetSessionValue(Of Integer)("uid")
I was trying to make it generic since in the end a query string value could be at least an integer or a string, but possibly also a double and others. But I get the error:
Value of 'String' cannot be converted to Type 'T'
I did this exact same thing with Session variables and it worked. Anyone know a way to make this work?
EDIT: Jonathan Allen below has a more simpler answer using CObj() or CTypeDynamic(). But the below also works from Convert string to nullable type (int, double, etc...)
Dim conv As TypeConverter = TypeDescriptor.GetConverter(GetType(T))
queryStringObject = DirectCast(conv.ConvertFrom(queryStringVariable), T)