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)
You can convert numbers to strings by using the strconv. Itoa method from the strconv package in the Go standard libary. If you pass either a number or a variable into the parentheses of the method, that numeric value will be converted into a string value.
The safest way is to use CTypeDynamic. This will ensure that implicit/explicit operators are used.
Function Convert(Of T)(s As String) As T
Return Microsoft.VisualBasic.CTypeDynamic(Of T)(s)
End Function
This will work for simple types but will fail for complex ones.
Function Convert(Of T)(s As String) As T
Return CType(CObj(s), T)
End Function
I think the issue is that you can't cast a string to an Integer (or indeed, many types). It needs to be parsed instead.
I'm not sure, but CType() might do the job instead of DirectCast().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With