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?
Casting is the process of converting one data type to another. For example, casting an Integer type to a String type. Some operations in VB.NET require specific data types to work. Casting creates the type you need.
CType is compiled inline, which means that the conversion code is part of the code that evaluates the expression. In some cases, the code runs faster because no procedures are called to perform the conversion.
Casting. Sometimes a programmer needs to change the data type of the contents of a variable. For example, an integer may need to be converted to a string in order to be displayed as part of a message. This process is known as casting .
Typecasting, or type conversion, is a method of changing an entity from one data type to another. It is used in computer programming to ensure variables are correctly processed by a function. An example of typecasting is converting an integer to a string.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With