Thursday, September 1, 2011

VB.NET Stupidisms - DirectCast over CType


I've been diving a bit more into vb.net development recently and decided for my own sanity it might be worthwhile to post some stupid simple notes on what I am learning as I go along.
The first has to do with using DirectCast instead of CType.  The easy answer is that DirectCast performance is marketably better.  The restriction is that you need to ensure you are essentially doing a cast as opposed to a conversion.
The better and longer answer that I'm going to quote directly from can be found in the repsonse to a question posted here.
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)











Hopefully this particular description was is as helpful to others as it was for me.

No comments:

Post a Comment