In VB.NET CINT(VB.NET) is Integer.Parse
in .NET Framework, what is the .NET equivalent for (VB.NET) CType?
views:
679answers:
3CType
is translated to a cast, which is a language level issue. In the emitted IL, there is no such thing as casting an object
to a string
, for instance. (Side note: if the type is a value type, it'll translate to an unbox
instruction, but it's another story; The runtime does not distinguish between a reference to Foo
and Bar
reference types at all, for the sake of simplicity, I also ignored throwing InvalidCastException
which is done by the castclass
instruction).
Integer.Parse
and CInt
basically do some process on the source object (the string) and convert it to an equivalent integer. They do something. CType
just instructs the language compiler about the type conversion.
For the sake of completeness, the IL equivalent of casting is:
castclass
if the type is a reference type.unbox
if the type is a value type.
However, the Visual Basic compiler, translates the expression to a call to one of the Microsoft.VisualBasic.CompilerServices.Conversions
methods.
For casting objects, CType()
works in VB, but not c# (unless you ref the Microsoft.VisualBasic.dll). You can also use DirectCast()
, or TryCast()
.
If you will be casting to a specific native type, you can use the methods in the Convert class to do this. (Not the same as Parse
/ TryParse
, those are hybrids of IsNumeric()
and CInt()
)
For example
Convert.ToInt32()
Convert.ToString()
Convert.ToBoolean()
There are a bunch of others for the various types.
You could always do something like this:
var thisInteger = (Int64)objectToconvert;
var thisComplicatedObject = (BAL.ComplicatedObject)objectToConvert;
Essentially put the type you need to convert to in the preceeding parens. This method doesn't bring back the nice intellisense that doing the ctype() operation does, you get it at the next line though.