Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting in VB.NET

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?

like image 979
Youssef Avatar asked Oct 30 '08 19:10

Youssef


People also ask

What is casting in VB net?

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.

What is CType in VB net?

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.

What is casting in programming?

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 .

What is type casting explain with example?

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.


2 Answers

 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.

like image 71
tom.dietrich Avatar answered Sep 18 '22 14:09

tom.dietrich


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?

like image 43
Joel Coehoorn Avatar answered Sep 17 '22 14:09

Joel Coehoorn