Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of 'String' cannot be converted to Type 'T'. Generic function for getting query strings?

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)
like image 351
SventoryMang Avatar asked Jul 21 '11 21:07

SventoryMang


People also ask

How to convert string* into string in Go?

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.


2 Answers

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
like image 165
Jonathan Allen Avatar answered Oct 15 '22 04:10

Jonathan Allen


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().

like image 20
Steve Morgan Avatar answered Oct 15 '22 04:10

Steve Morgan