Alex Rivera | Logout

VB.NET Generic Function

Asked 2009-07-29T19:37:32.400
10

What I want to do is, based on the type of T do different opperations. Below is a simple example of my problem.

Public Shared Function Example(Of T)() As T
    Dim retval As T
    If TypeOf retval Is String Then
        Dim myString As String = "Hello"
        retval = myString
    ElseIf TypeOf retval Is Integer Then
        Dim myInt As Integer = 101
        retval = myInt
    End If
    Return retval
End Function

I get the error "Value of Type 'String' Cannot be converted to 'T'" Same with the integer part. If I cast either to an object before asigning them to retval it works but I think that would defeat my purpose and be less efficient. Any Ideas? Thanks!

Edit
Report

2 Answers

1
retVal = (T) "Hello World!"
answered 2009-07-29T19:43:13.590
0

Do retval = Ctype(Mystring, T) or retVal = Ctype(MyInt, T)

answered 2009-07-29T19:41:52.687

Your Answer