Charles Okwuagwu
Charles Okwuagwu

Reputation: 10866

How To: Use a Type definition returned from a function?

Please how can I use a Type definition returned from a function?

The function below compiles, but I get: BC30002 "Type 'DB.ResolveType' is not defined." when i try to use it

Public NotInheritable Class DB
    Public Shared Function ResolveType(type As String) As Type
        Select Case type
            Case "Stop-Action-Request" : Return GetType(cheque_action)
            Case "Cheque-Book-Request" : Return GetType(cheque_book_request)
            Case "Confirm-Action-Request" : Return GetType(cheque_action)
            Case "FX-Transfer-Request" : Return GetType(cheque_action)
            Case "Mobile-Banking-Request" : Return GetType(mobile_banking_request)
            Case "SMS-Alerts-Request" : Return GetType(sms_alert_request)
        End Select

        Return Nothing
    End Function
End Class

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Dim d = Request.Form("payload")

            Dim r = JsonConvert.DeserializeObject(Of request)(d)

            ** this line fails: **
            Dim p = JsonConvert.DeserializeObject(Of DB.ResolveType(r.req_type))(r.data)

            DB.new_request(r.req_type, r.src, r.data)
        Catch ex As Exception

        End Try
    End Sub

Upvotes: 0

Views: 32

Answers (2)

Alex B.
Alex B.

Reputation: 2167

You cannot use generics like that.

If you have a generic method you have to provide a constant defined type which is known at compile-time, e.g. JsonConvert.DeserializeObject(Of String)(data)

In your example, you try to provide a type which is dynamically resolved during run-time which is not possible.

Just use an other overload of DeserializeObject if you want to the object type to be dynamically resolved, e.g.

JsonConvert.DeserializeObject(r.data, DB.ResolveType(r.req_type))

Upvotes: 1

anion
anion

Reputation: 2049

your return-statements seem to be correct. but you can not write something like "DeserializeObject(Of DB.ResolveType(r.req_type))(r.data)"

generics operations can have types as arguments (example: " Dim p = MyType.MyFunction(of String)(argument)") but you can not use an obbject (of the type "Type" or any other type) instead of the type-argument

Upvotes: 0

Related Questions