473,287 Members | 3,319 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

DirectCast vs CType

Ot
I apparently have a bit to learn about Casting and Conversion. I have been
thinking of them as the same but a discussion in another thread leads me to
believe that this is wrong thinking.

I found this in the VB Language reference:
<quote>
The DirectCast keyword introduces a type conversion operation. You use it
the same way you use the CType keyword....

Both keywords take an expression to be converted as the first argument, and
the type to convert it to as the second argument. Both conversions fail if
there is no conversion defined between the data type of the expression and
the data type specified as the second argument.
The difference between the two keywords is that CType succeeds as long as
there is a valid conversion defined between the expression and the type,
whereas DirectCast requires the run-time type of an object variable to be
the same as the specified type. If the specified type and the run-time type
of the expression are the same, however, the run-time performance of
DirectCast is better than that of CType.

DirectCast is special in that conversions from type Object to any other
type are performed as a direct cast down the hierarchy - all of the special
conversion behaviors from Object are ignored.

</quote>

This last sentence is a bit unclear to me. I am not sure what "special
conversion behaviors" might be in an Object.

Further, it says that DirectCast conversions are "performed as a direct
cast down the hierarchy..." which may be true but is decidedly unhelpful if
one doesn't know what a "direct cast" is in the first place.

----------------------

"DirectCast requires the run-time type of an object variable to be
the same as the specified type. If the specified type and the run-time type
of the expression are the same, however, the run-time performance of
DirectCast is better than that of CType."

My interpretation: An object to be DirectCast must already be of the
desired type. If you know this in advance, DirectCast is faster than
CType.

Thanks in advance,
Ot

Nov 20 '05 #1
6 10797
Hi,

Directcast is faster. See the Conversion Functions, CType,
DirectCast, and System.Convert section for more info.

http://msdn.microsoft.com/library/de...tinternals.asp

Ken
-----------------
"Ot" <ur***@tds.invalid (use net)> wrote in message
news:uI**************@TK2MSFTNGP11.phx.gbl...
I apparently have a bit to learn about Casting and Conversion. I have been
thinking of them as the same but a discussion in another thread leads me
to
believe that this is wrong thinking.

I found this in the VB Language reference:
<quote>
The DirectCast keyword introduces a type conversion operation. You use it
the same way you use the CType keyword....

Both keywords take an expression to be converted as the first argument,
and
the type to convert it to as the second argument. Both conversions fail if
there is no conversion defined between the data type of the expression and
the data type specified as the second argument.
The difference between the two keywords is that CType succeeds as long as
there is a valid conversion defined between the expression and the type,
whereas DirectCast requires the run-time type of an object variable to be
the same as the specified type. If the specified type and the run-time
type
of the expression are the same, however, the run-time performance of
DirectCast is better than that of CType.

DirectCast is special in that conversions from type Object to any other
type are performed as a direct cast down the hierarchy - all of the
special
conversion behaviors from Object are ignored.

</quote>

This last sentence is a bit unclear to me. I am not sure what "special
conversion behaviors" might be in an Object.

Further, it says that DirectCast conversions are "performed as a direct
cast down the hierarchy..." which may be true but is decidedly unhelpful
if
one doesn't know what a "direct cast" is in the first place.

----------------------

"DirectCast requires the run-time type of an object variable to be
the same as the specified type. If the specified type and the run-time
type
of the expression are the same, however, the run-time performance of
DirectCast is better than that of CType."

My interpretation: An object to be DirectCast must already be of the
desired type. If you know this in advance, DirectCast is faster than
CType.

Thanks in advance,
Ot

Nov 20 '05 #2
OT,

Here's a quick outline of the differences and recommendations of where you
should ctype and directcast (IHMO anyway)

1) CType is capable of a *cast* or a *conversion*. DirectCast can only
*cast*

By "conversion" I mean converting one datatype to another (e.g. string to
integer, decimal to integer, object to string etc).

By "cast" I mean changing one type of object into another type that is
related to it by one of the following rules:

a) The type you're converting the object to must be the same type
e.g.
--------------
Dim a as String = "hello"
Dim b as Object = a
Dim c as string = directcast(b, String)
--------------

Variable b is an object that holds a string, so you can cast it to a string.

b) If converting to an interface, the type you're converting must implement
the interface
e.g.
---------------------
Dim a as New MyInterfaceObejct
Dim b as IInterface = directcast(a, IInterface)
----------------------

c) If converting to a derived type, the runtime type of the object must be
the derived type or one of it's own derived types :S
e.g.
----------------------
Dim a as Base = New Derived
Dim b as Derived = directcast(a, Derived)
----------------------

2) Use directcast whenever a "type relationship" exists - it is slightly
faster (in some cases anyway), but forces you to be more aware of
conversions that are going on.

3) Use Ctype when a type relationship doesn't exist, but a value
relationship does (e.g. converting the string "123" to the integer 123)

The difference has been discussed a lot latley in this group. Have a look at
the following for more reference:

http://tinyurl.com/3e8rg
http://tinyurl.com/3ensw
HTH,

Trev.
Nov 20 '05 #3
Cor
Hi Ot,

I thought why am I almost never using CType, and when I saw the answer from
Trev I knew.

I use in that kind of situations mostly
Cdate,
Cint
Cdouble
..tostring

In all other situations it is with me
Directcast (there should be a shortcut on the keyboard for that I think)

Cor
Nov 20 '05 #4
Ot,
My interpretation: An object to be DirectCast must already be of the
desired type. If you know this in advance, DirectCast is faster than
CType. In a nut shell that is it!

DirectCast will only allow the cast if the parameter is already of the
requested type. Where as CType will find a routine to do a conversion if
available.

For example:
Dim o1 As Object
Dim o2 As Object
Dim i As Integer
o1 = 1 ' o1 contains a boxed Integer
o2 = "1" ' o2 contains a string

' This works as o1 contains an integer
i = DirectCast(o1, Integer)

' This fails as o2 really contains a string
i = DirectCast(o2, Integer)

' this works as there is a conversion from String to Integer
i = CType(o2, Integer)

Further, it says that DirectCast conversions are "performed as a direct
cast down the hierarchy..." which may be true but is decidedly unhelpful if one doesn't know what a "direct cast" is in the first place. Casting deals with inheritance and what types a variable looks like, it
looks at both Inherits & Implements keywords. When you use Cast you are
changing what type the variable looks like, not actually changing what type
it is. For example System.IO.Stream: System.IO.MemoryStream inherits from
Stream so a Memory stream is of type MemoryStream and it is also of type
Stream. MemoryStream is "down the hierarchy" from Stream, so if you have a
Stream variable that contains a MemoryStream object, you can use DirectCast
to look at that variable in its true form a MemoryStream.

You do understand that when Class1 Inherits from Class2 that Class1 is both
the Class1 type & the Class2 type? And that when Class1 Implements
Interface1, that Class1 is both the Class1 type & the Interface1 type? As
understanding how Inherits & Implements work is needed to understand how
casting works...

However in my example above, String does not inherit (or implement) from
Integer, nor Integer from String, hence the DirectCast does not work, where
as CType knows there is a routine that will convert (change the type) of
String into Integer, hence it does work.

Hope this helps
Jay
"Ot" <ur***@tds.invalid (use net)> wrote in message
news:uI**************@TK2MSFTNGP11.phx.gbl... I apparently have a bit to learn about Casting and Conversion. I have been thinking of them as the same but a discussion in another thread leads me to believe that this is wrong thinking.

I found this in the VB Language reference:
<quote>
The DirectCast keyword introduces a type conversion operation. You use it
the same way you use the CType keyword....

Both keywords take an expression to be converted as the first argument, and the type to convert it to as the second argument. Both conversions fail if
there is no conversion defined between the data type of the expression and
the data type specified as the second argument.
The difference between the two keywords is that CType succeeds as long as
there is a valid conversion defined between the expression and the type,
whereas DirectCast requires the run-time type of an object variable to be
the same as the specified type. If the specified type and the run-time type of the expression are the same, however, the run-time performance of
DirectCast is better than that of CType.

DirectCast is special in that conversions from type Object to any other
type are performed as a direct cast down the hierarchy - all of the special conversion behaviors from Object are ignored.

</quote>

This last sentence is a bit unclear to me. I am not sure what "special
conversion behaviors" might be in an Object.

Further, it says that DirectCast conversions are "performed as a direct
cast down the hierarchy..." which may be true but is decidedly unhelpful if one doesn't know what a "direct cast" is in the first place.

----------------------

"DirectCast requires the run-time type of an object variable to be
the same as the specified type. If the specified type and the run-time type of the expression are the same, however, the run-time performance of
DirectCast is better than that of CType."

My interpretation: An object to be DirectCast must already be of the
desired type. If you know this in advance, DirectCast is faster than
CType.

Thanks in advance,
Ot

Nov 20 '05 #5
Ot
Thank you all, your responses are appreciated.

Jay,

I think I have it....

Class A

Class B
inherits A

Class C
inherits B

Class D
inherits C

In that case if I have an object that is an instance of D I could cast it
to any of A,B,C,D.

However an object of class C could be cast as A,B or C, but not D.

If I use, say, a hashtable to store some integers and later get them (they
are objects when they come back). I could CDbl(o) but not
DirectCast(o,Long) because the object is really an Integer which is not
also a Long or Double even though a conversion exists.

Regards,
Ot

"Jay B. Harlow [MVP - Outlook]" <Ja************@msn.com> wrote in message
news:eX**************@TK2MSFTNGP11.phx.gbl...
Ot,
My interpretation: An object to be DirectCast must already be of the
desired type. If you know this in advance, DirectCast is faster than
CType. In a nut shell that is it!

DirectCast will only allow the cast if the parameter is already of the
requested type. Where as CType will find a routine to do a conversion if
available.

For example:
Dim o1 As Object
Dim o2 As Object
Dim i As Integer
o1 = 1 ' o1 contains a boxed Integer
o2 = "1" ' o2 contains a string

' This works as o1 contains an integer
i = DirectCast(o1, Integer)

' This fails as o2 really contains a string
i = DirectCast(o2, Integer)

' this works as there is a conversion from String to Integer
i = CType(o2, Integer)

Further, it says that DirectCast conversions are "performed as a direct
cast down the hierarchy..." which may be true but is decidedly unhelpful if
one doesn't know what a "direct cast" is in the first place. Casting deals with inheritance and what types a variable looks like, it
looks at both Inherits & Implements keywords. When you use Cast you are
changing what type the variable looks like, not actually changing what

type it is. For example System.IO.Stream: System.IO.MemoryStream inherits from
Stream so a Memory stream is of type MemoryStream and it is also of type
Stream. MemoryStream is "down the hierarchy" from Stream, so if you have a Stream variable that contains a MemoryStream object, you can use DirectCast to look at that variable in its true form a MemoryStream.

You do understand that when Class1 Inherits from Class2 that Class1 is both the Class1 type & the Class2 type? And that when Class1 Implements
Interface1, that Class1 is both the Class1 type & the Interface1 type? As
understanding how Inherits & Implements work is needed to understand how
casting works...

However in my example above, String does not inherit (or implement) from
Integer, nor Integer from String, hence the DirectCast does not work, where as CType knows there is a routine that will convert (change the type) of
String into Integer, hence it does work.

Hope this helps
Jay
"Ot" <ur***@tds.invalid (use net)> wrote in message
news:uI**************@TK2MSFTNGP11.phx.gbl...
I apparently have a bit to learn about Casting and Conversion. I have been
thinking of them as the same but a discussion in another thread leads

me to
believe that this is wrong thinking.

I found this in the VB Language reference:
<quote>
The DirectCast keyword introduces a type conversion operation. You use
it the same way you use the CType keyword....

Both keywords take an expression to be converted as the first argument,

and
the type to convert it to as the second argument. Both conversions fail if there is no conversion defined between the data type of the expression and the data type specified as the second argument.
The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type, whereas DirectCast requires the run-time type of an object variable to be the same as the specified type. If the specified type and the run-time

type
of the expression are the same, however, the run-time performance of
DirectCast is better than that of CType.

DirectCast is special in that conversions from type Object to any other
type are performed as a direct cast down the hierarchy - all of the

special
conversion behaviors from Object are ignored.

</quote>

This last sentence is a bit unclear to me. I am not sure what "special
conversion behaviors" might be in an Object.

Further, it says that DirectCast conversions are "performed as a direct
cast down the hierarchy..." which may be true but is decidedly

unhelpful if
one doesn't know what a "direct cast" is in the first place.

----------------------

"DirectCast requires the run-time type of an object variable to be
the same as the specified type. If the specified type and the run-time

type
of the expression are the same, however, the run-time performance of
DirectCast is better than that of CType."

My interpretation: An object to be DirectCast must already be of the
desired type. If you know this in advance, DirectCast is faster than
CType.

Thanks in advance,
Ot


Nov 20 '05 #6
Ot,
Looks like you got it.

Jay

"Ot" <ur***@tds.invalid (use net)> wrote in message
news:O2****************@TK2MSFTNGP10.phx.gbl...
Thank you all, your responses are appreciated.

Jay,

I think I have it....

Class A

Class B
inherits A

Class C
inherits B

Class D
inherits C

In that case if I have an object that is an instance of D I could cast it
to any of A,B,C,D.

However an object of class C could be cast as A,B or C, but not D.

If I use, say, a hashtable to store some integers and later get them (they
are objects when they come back). I could CDbl(o) but not
DirectCast(o,Long) because the object is really an Integer which is not
also a Long or Double even though a conversion exists.

Regards,
Ot

"Jay B. Harlow [MVP - Outlook]" <Ja************@msn.com> wrote in message
news:eX**************@TK2MSFTNGP11.phx.gbl...
Ot,
My interpretation: An object to be DirectCast must already be of the
desired type. If you know this in advance, DirectCast is faster than
CType. In a nut shell that is it!

DirectCast will only allow the cast if the parameter is already of the
requested type. Where as CType will find a routine to do a conversion if
available.

For example:
Dim o1 As Object
Dim o2 As Object
Dim i As Integer
o1 = 1 ' o1 contains a boxed Integer
o2 = "1" ' o2 contains a string

' This works as o1 contains an integer
i = DirectCast(o1, Integer)

' This fails as o2 really contains a string
i = DirectCast(o2, Integer)

' this works as there is a conversion from String to Integer
i = CType(o2, Integer)

Further, it says that DirectCast conversions are "performed as a direct cast down the hierarchy..." which may be true but is decidedly unhelpful
if
one doesn't know what a "direct cast" is in the first place.

Casting deals with inheritance and what types a variable looks like, it
looks at both Inherits & Implements keywords. When you use Cast you are
changing what type the variable looks like, not actually changing what

type
it is. For example System.IO.Stream: System.IO.MemoryStream inherits from Stream so a Memory stream is of type MemoryStream and it is also of type
Stream. MemoryStream is "down the hierarchy" from Stream, so if you have

a
Stream variable that contains a MemoryStream object, you can use

DirectCast
to look at that variable in its true form a MemoryStream.

You do understand that when Class1 Inherits from Class2 that Class1 is

both
the Class1 type & the Class2 type? And that when Class1 Implements
Interface1, that Class1 is both the Class1 type & the Interface1 type? As understanding how Inherits & Implements work is needed to understand how
casting works...

However in my example above, String does not inherit (or implement) from
Integer, nor Integer from String, hence the DirectCast does not work,

where
as CType knows there is a routine that will convert (change the type) of
String into Integer, hence it does work.

Hope this helps
Jay
"Ot" <ur***@tds.invalid (use net)> wrote in message
news:uI**************@TK2MSFTNGP11.phx.gbl...
I apparently have a bit to learn about Casting and Conversion. I have

been
thinking of them as the same but a discussion in another thread leads me
to
believe that this is wrong thinking.

I found this in the VB Language reference:
<quote>
The DirectCast keyword introduces a type conversion operation. You use

it the same way you use the CType keyword....

Both keywords take an expression to be converted as the first argument, and
the type to convert it to as the second argument. Both conversions
fail if there is no conversion defined between the data type of the expression and the data type specified as the second argument.
The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type, whereas DirectCast requires the run-time type of an object variable to be the same as the specified type. If the specified type and the run-time

type
of the expression are the same, however, the run-time performance of
DirectCast is better than that of CType.

DirectCast is special in that conversions from type Object to any

other type are performed as a direct cast down the hierarchy - all of the

special
conversion behaviors from Object are ignored.

</quote>

This last sentence is a bit unclear to me. I am not sure what "special conversion behaviors" might be in an Object.

Further, it says that DirectCast conversions are "performed as a direct cast down the hierarchy..." which may be true but is decidedly

unhelpful
if
one doesn't know what a "direct cast" is in the first place.

----------------------

"DirectCast requires the run-time type of an object variable to be
the same as the specified type. If the specified type and the run-time

type
of the expression are the same, however, the run-time performance of
DirectCast is better than that of CType."

My interpretation: An object to be DirectCast must already be of the
desired type. If you know this in advance, DirectCast is faster than
CType.

Thanks in advance,
Ot



Nov 20 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Andreas Klemt | last post by:
Hello, what has the better performance and what are you using? Dim myObj As Object = 70 a) Dim myInt As Integer = DirectCast(myObj, Integer) b) Dim myInt As Integer = Convert.ToInt32(myObj) ...
11
by: Tubs | last post by:
i am attempting to write something which can morph itself to whatever comes in and get the value property from it but i don't know what type it is until runtime. I am therefore trying to use...
13
by: Crirus | last post by:
Can I use DirectCast to convert a object to it's base or should I use CType? I have a instance of a class as Object. The run-time tipe is a derived of a class, but I need to refer to that instance...
5
by: Michael Ramey | last post by:
Hello, There are quite a few ways to convert one object, say an integer to a string. Dim myStr as string dim myInt as integer = 123 myStr = cstr(myInt) myStr = myInt.toString()
6
by: Mark Nethercott | last post by:
I get the following failure when trying to access the builtin properties; An unhandled exception of type 'System.InvalidCastException' occurred in resultsoutput.dll Additional information:...
7
by: Brian Henry | last post by:
is there any speed diffrences between doing Ctype or directcast? I know about the inherite diffrences, but process usage time wise, does one take up more cycles then the other? thanks
1
by: iwdu15 | last post by:
can anyone explain the directcast code...ive tried using it and lookin it up but im lookin for an easy definition and how it works...ive tried using it before byut it throws errors saying it can...
4
by: Vagabond Software | last post by:
Here is the code: Dim amountDue As Double amountDue = Math.Round(DirectCast(strOrderTotal, Double), 2) This code produces an invalid cast exception. The String variable strOrderTotal...
3
by: =?Utf-8?B?TWlrZQ==?= | last post by:
If Visual Studio knows the type, why does the system-generated property use CType instead of DirectCast? DirectCast is more efficient right? For example - Here's what we have for a setting...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.