Question

I would like to be able to cast a value dynamically where the type is known only at runtime. Something like this:

myvalue = CType(value, "String, Integer or Boolean")

The string that contains the type value is passed as an argument and is also read from a database, and the value is stored as string in the database.

Is this possible?

Was it helpful?

Solution

Sure, but myvalue will have to be defined as of type Object, and you don't necessarily want that. Perhaps this is a case better served by generics.

What determines what type will be used?

OTHER TIPS

 Dim bMyValue As Boolean
 Dim iMyValue As Integer
 Dim sMyValue As String 
 Dim t As Type = myValue.GetType


 Select Case t.Name
     Case "String"
        sMyValue = ctype(myValue, string)
     Case "Boolean"
        bMyValue = ctype(myValue, boolean)
     Case "Integer"
        iMyValue = ctype(myValue, Integer)
 End Select

It's a bit hacky but it works.

This is the shortest way to do it. I've tested it with multiple types.

Sub DoCast(ByVal something As Object)

    Dim newSomething = Convert.ChangeType(something, something.GetType())

End Sub

Well, how do you determine which type is required? As Joel said, this is probably a case for generics. The thing is: since you don't know the type at compile time, you can't treat the value returned anyway so casting doesn't really make sense here.

Maybe instead of dynamically casting something (which doesn't seem to work) you could use reflection instead. It is easy enough to get and invoke specific methods or properties.

Dim t As Type = testObject.GetType()
Dim prop As PropertyInfo = t.GetProperty("propertyName")
Dim gmi As MethodInfo = prop.GetGetMethod()
gmi.Invoke(testObject, Nothing)

It isn't pretty but you could do some of that in one line instead of so many.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top