Reputation: 728
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?
Upvotes: 14
Views: 42363
Reputation: 415630
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?
Upvotes: 7
Reputation: 20794
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
Upvotes: 5
Reputation: 8347
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.
Upvotes: 9
Reputation: 5422
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.
Upvotes: 2
Reputation: 545518
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.
Upvotes: 4